每当我读取文件时,Perl似乎都在杀死我的数组:
my @files = ("foo", "bar", "baz"); print "Files: " . join(" ", @files) . "\n"; foreach(@files) { print "The file is $_\n"; func(); } sub func { open(READ, "< test.txt"); while() { } close READ; } print "Files: " . join(" ", @files) . "\n";
生产:
Files: foo bar baz The file is foo The file is bar The file is baz Files:
但是当我发表评论时func()
,它给出了我所期望的:
Files: foo bar baz The file is foo The file is bar The file is baz Files: foo bar baz
任何想法为什么会这样?
您必须更改foo
为本地化$_
,或不在$_
循环中使用.最好的,做到两个:
foreach my $filename (@files) { print "The file is $filename\n"; func(); } sub func { local $_; open my $read, '<', 'test.txt' or die "Couldn't open test.txt: $!"; while(<$read>) { } close $read or die "Couldn't close file: $!"; }
foreach循环别名$_
为文件的当前名称并while(
分配给$_
.这就是魔术的糟糕组合,可以这么说.
一般来说,除了单线之外,依靠$_
其他任何东西都是一个坏主意.