开发者

How to get the current line number of a file opened using Perl

开发者 https://www.devze.com 2023-03-03 19:49 出处:网络
open my $fp, \'<\', $开发者_如何学运维file or die $!; while (<$fp>) { my $line = $_; if ($line =~ /$regex/) {
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.

0

精彩评论

暂无评论...
验证码 换一张
取 消