这是一些用于在文件中查找单词、字符、行的代码。有人能解释一下 while 循环吗?
open(FILE, "<data.txt") or die "Could not open file: $!";
my ($lines, $words, $chars) = (0,0,0);
while (<FILE>) {
$lines++;
$chars += length($_); //what _ stands for?
$words += scalar(split(/\s+/, $_)); //what is /\s+/, $_
}
print("lines=$lines words=$words chars=$chars\n");
答案1
答案2
假设它是 Perl,(你应该已经说清楚了)。
阅读man perlintro
,其中部分内容如下:
Files and I/O
You can open a file for input or output using the "open()" function.
It's documented in extravagant detail in perlfunc and perlopentut, but
in short:
open(my $in, "<", "input.txt") or die "Can't open input.txt: $!";
open(my $out, ">", "output.txt") or die "Can't open output.txt: $!";
open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
You can read from an open filehandle using the "<>" operator. In
scalar context it reads a single line from the filehandle, and in list
context it reads the whole file in, assigning each line to an element
of the list:
my $line = <$in>;
my @lines = <$in>;
如果这还不够,请阅读man perlfunc
并man perlopentut