请解释 PERL 代码中的 while 循环?

请解释 PERL 代码中的 while 循环?

这是一些用于在文件中查找单词、字符、行的代码。有人能解释一下 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

<>是菱形运算符。在 while 循环中使用它与

while (defined($_ = readline FILE)) {

因此,它逐行读取文件,将每行的内容分配给主题变量$_

++运算符将变量加一。

运算+=符将右侧的值添加到左侧。长度返回字符串的长度。

分裂使用正则表达式拆分字符串。此处,\s+使用表示一个或多个空格字符。调用标量结果返回所获得的元素的数量。

答案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 perlfuncman perlopentut

相关内容