Reputation: 94810
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;
Upvotes: 34
Views: 44518
Reputation: 2038
Here is explained why we should avoid using $.
, nor $_
(or any global variable). Instead:
while(my $line = <FILE>) {
print $line unless ${\*FILE}->input_line_number == 1;
}
To avoid this and a lot of others Perl gotchas, we can use text editors plugins/packages like linter-perl. Due to these issues, some people believe Perl is a write-only language.
Upvotes: -3
Reputation: 5308
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.
Upvotes: 16