Nat*_*enn 5 perl file-handling special-variables
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
}
Run Code Online (Sandbox Code Playgroud)
以下是所有三个文件的内容:
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10
Run Code Online (Sandbox Code Playgroud)
因为我没有显式调用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
Run Code Online (Sandbox Code Playgroud)
肯定看起来它正在重置给我.我对文档的理解是错误的吗?有人可以告诉我什么情况隐含close不会重置$.?
顺便说一下,我正在使用草莓5.16.1.
$.实际上并不是一个全局变量,它是最近读取的文件句柄的属性.并且您在循环的每次迭代中使用新的文件句柄.
像这样修改你的代码"修复"它:
my $fh;
for my $file (@files){
open $fh, '<', $file;
Run Code Online (Sandbox Code Playgroud)