如何使用Perl打开文件的当前行号?

时间:2022-09-18 07:29:11
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;

2 个解决方案

#1


41  

Use $. (see perldoc perlvar).

使用$。 (见perldoc perlvar)。

#2


13  

You can also do it through OO interface:

您也可以通过OO界面完成:

use IO::Handle;
# later on ...
my $n = $fp->input_line_number();

This is in perldoc perlvar, too.

这也是perldoc perlvar。

#1


41  

Use $. (see perldoc perlvar).

使用$。 (见perldoc perlvar)。

#2


13  

You can also do it through OO interface:

您也可以通过OO界面完成:

use IO::Handle;
# later on ...
my $n = $fp->input_line_number();

This is in perldoc perlvar, too.

这也是perldoc perlvar。