Lazer
Lazer

Reputation: 94810

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;

Upvotes: 34

Views: 44518

Answers (3)

Pablo Bianchi
Pablo Bianchi

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

Dallaylaen
Dallaylaen

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

ninjalj
ninjalj

Reputation: 43688

Use $. (see perldoc perlvar).

Upvotes: 57

Related Questions