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

前端 未结 3 2025
不思量自难忘°
不思量自难忘° 2021-01-03 19:21
open my $fp, \'<\', $file or die $!;

while (<$fp>) {
    my $line = $_;
    if ($line =~ /$regex/) {
        # How do I find out which line number this mat         


        
相关标签:
3条回答
  • 2021-01-03 19:42

    Don't use $., nor $_ or any global variable. Use this instead:

    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 on Atom or VSCode packages like linter-perl. Stop making Perl a write-only language!

    0 讨论(0)
  • 2021-01-03 19:44

    Use $. (see perldoc perlvar).

    0 讨论(0)
  • 2021-01-03 19:59

    You can also do it through OO interface:

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

    This is in perldoc perlvar, too.

    0 讨论(0)
提交回复
热议问题