'How to get the current line number of a file opened using Perl
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;
Solution 1:[1]
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.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Mortensen |
| Solution 2 |
