如何重置$.?

Aru*_*ngh 1 perl file-handling

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

我想tail在Perl中模拟Unix 命令并从文件中打印最后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);
Run Code Online (Sandbox Code Playgroud)

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

cho*_*oba 5

使用localwith $.会做出比你想象的更多的事情:

本地化$.不会本地化文件句柄的行数.相反,它将本地化​​perl的文件句柄$的概念.目前是别名的.

$. 不是只读的,可以正常分配.

1 while <$fh>;
my $i = $.;
seek $fh, $. = 0, 0;
Run Code Online (Sandbox Code Playgroud)