6

如果您使用隐式关闭完成,则Perl状态的文档不会重置。我试图确切地了解这意味着什么,但无法实现。这是我的脚本:close$.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。

4

1 回答 1

10

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

像这样修改代码“修复”它:

my $fh;
for my $file (@files){
    open $fh, '<', $file;
于 2013-01-25T00:42:05.013 回答