Perl隐式关闭重置$。变量

时间:2013-01-25 00:39:31

标签: perl file-handling special-variables

Perl close的{​​{3}}表示如果您使用$.隐式关闭​​,则open不会重置。我试图确切地看到这意味着什么,但无法让它发生。这是我的剧本:

use strict;
use warnings;
use autodie;
my @files = qw(test1.txt test2.txt test3.txt);

#try with implicit close
for my $file (@files){
    open my $fh, '<', $file;
    while(<$fh>){
        chomp;
        print "line $. is $_\n";
    }
    #implicit close here
}

以下是所有三个文件的内容:

line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10

由于我没有明确调用close,因此应使用隐式close(我认为),并且不应重置$.。但是,当我运行脚本时,我得到这个输出,显示$。重置:

line 1 is line 1
line 2 is line 2
line 3 is line 3
line 4 is line 4
line 5 is line 5
line 6 is line 6
line 7 is line 7
line 8 is line 8
line 9 is line 9
line 10 is line 10
line 1 is line 1
line 2 is line 2
line 3 is line 3
line 4 is line 4
line 5 is line 5
line 6 is line 6
line 7 is line 7
line 8 is line 8
line 9 is line 9
line 10 is line 10
line 1 is line 1
line 2 is line 2
line 3 is line 3
line 4 is line 4
line 5 is line 5
line 6 is line 6
line 7 is line 7
line 8 is line 8
line 9 is line 9
line 10 is line 10

看起来它似乎正在重置给我。我对文档的理解是错误的吗?有人可以告诉我隐含的close在什么情况下不会重置$.

顺便说一句,我正在使用草莓5.16.1。

1 个答案:

答案 0 :(得分:9)

$.实际上不是全局变量,它是最近读取的文件句柄的属性。而且你在循环的每次迭代中都使用了一个新的文件句柄。

修改代码就像“修复”它一样:

my $fh;
for my $file (@files){
    open $fh, '<', $file;