[英]Why does calling this function change my array?
Perl seems to be killing my array whenever I read a file: 每当我读取文件时,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(<READ>) {
}
close READ;
}
print "Files: " . join(" ", @files) . "\n";
produces: 生产:
Files: foo bar baz
The file is foo
The file is bar
The file is baz
Files:
but when I comment out func()
, it gives what I would've expected: 但是当我注释掉func()
,它给出了我所期望的:
Files: foo bar baz
The file is foo
The file is bar
The file is baz
Files: foo bar baz
Any ideas why this might be happening? 任何想法为什么会这样?
You have to change foo
to localize $_
, or not to use $_
in your loop. 你必须改变foo
来本地化$_
,或者不要在你的循环中使用$_
。 Best yet, do both: 最好的,做到两个:
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: $!";
}
The foreach loop aliases $_
to the current name of the file and the while(<READ>)
assigns to $_
. foreach循环将$_
替换$_
文件的当前名称, while(<READ>)
指定给$_
。 That's a bad combination of magic, so to say. 这就是魔术的糟糕组合,可以这么说。
In general, it's a bad idea to rely on much on $_
for anything other than a one-liner. 一般来说,除了单行之外,依靠$_
任何事情都是一个坏主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.