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(<READ>) {
}
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
为什么会发生这种情况的任何想法?
答案 0 :(得分:12)
您必须将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(<READ>)
分配给$_
。这就是魔术的糟糕组合,可以这么说。
一般来说,将$_
用于除了单行之外的其他任何事情都是一个坏主意。