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