open my $fp, '<', $开发者_如何学运维file or die $!;
while (<$fp>) {
my $line = $_;
if ($line =~ /$regex/) {
# How do I find out which line number this match happened at?
}
}
close $fp;
Use $.
(see perldoc perlvar
).
You can also do it through an OO interface:
use IO::Handle;
# later on ...
my $n = $fp->input_line_number();
This is in perldoc perlvar, too.
Avoid using $.
, nor $_
or any global variable. Here's a good answer explaining why. Instead you could use:
while(my $line = <FILE>) {
print $line unless ${\*FILE}->input_line_number == 1;
}
To avoid this and a lot of others Perl gotchas, you can use Atom or Visual Studio Code packages like linter-perl. Due to these issues some people believe Perl is a write-only language.
精彩评论