如何重置$.?

How to reset $.?

我知道 $.$/ 设置为 "\n" 时显示行号。

我想在 Perl 中模拟 Unix tail 命令并打印文件的最后 10 行,但 $. 不起作用。如果文件包含 14 行,则在下一个循环中从 15 行开始。

#!/usr/bin/perl
use strict;
use warnings;

my $i;

open my $fh, '<', $ARGV[0] or die "unable to open file $ARGV[0] :$! \n";
do { local $.; $i = $. } while (<$fh>);
seek $fh, 0, 0;

if ($i > 10) {
    $i = $i - 10;
    print "$i \n";
    while (<$fh>) {

        #local $.;# tried doesn't work
        #undef $.; #tried doesn't work

        print "$. $_" if ($. > $i);
    }
}
else {
    print "$_" while (<$fh>);
}

close($fh);

我想重置 $. 以便在下一个循环中有用。

您必须重新打开文件句柄。否则,正如您所发现的,行号会继续递增

#!/usr/bin/perl
use strict;
use warnings;

my ($filename) = @ARGV;

my $num_lines;
open my $fh, '<', $filename or die qq{Unable to open file "$filename" for input: $!\n};
++$num_lines while <$fh>;

open $fh, '<', $filename or die qq{Unable to open file "$filename" for input: $!\n};

print "$num_lines lines\n";
while ( <$fh> ) {
    print "$. $_" if $. > $num_lines - 10;
}

这里有一个更简洁的方法

#!/usr/bin/perl
use strict;
use warnings;

my ($filename) = @ARGV;

my @lines;
open my $fh, '<', $filename or die qq{Unable to open file "$filename" for input: $!\n};

while ( <$fh> ) {
  push @lines, $_;
  shift @lines while @lines > 10;
}

print @lines;

local$. 结合使用可以做一些超出您想象的事情:

Localizing $. will not localize the filehandle's line count. Instead, it will localize perl's notion of which filehandle $. is currently aliased to.

$.不是只读的,可以正常赋值。

1 while <$fh>;
my $i = $.;
seek $fh, $. = 0, 0;