只需在每次读取一行时递增一个计数器.
my $line;
while (<>) {
++$line;
print "$line: $_" if /foo/;
}
Run Code Online (Sandbox Code Playgroud)
也就是说,Perl已经为你做到了.
while (<>) {
print "$.: $_" if /foo/;
}
Run Code Online (Sandbox Code Playgroud)
如果要支持多个文件,
while (<>) {
print "$ARGV:$.: $_" if /foo/;
close(ARGV) if eof; # Reset line counter for each file.
}
Run Code Online (Sandbox Code Playgroud)
(缺乏parens eof是重要的.)