我以为我了解 map ,但是以下结果我不明白。我知道它为什么会发生,我只是不知道它是如何发生的。
问题是@array 的内容正在改变,因为 $_
正在_do_stuff_to_file
期间被重置称呼。所以打印的是here: \nhere:\n
当我期望它是 here: donkie\nhere: kong\n
.
注:这不是经过测试的代码。这只是我记得从实验室看到的。为什么@array
的内容是改变?
如果我设置 $_
至 $f
在从 _some_func
返回 1 之前.然后阵列仍然完好无损。
这是一个示例程序来说明我所看到的:
my @array = ("donkie", "kong");
map { push @junk, _some_func('blah', $_); } @array;
if (join ('', @junk) !~ /0/)
{ # for example sake this is always true since return 1 from _some_func.
print map { "here: $_\n"; } @array;
}
sub _some_func
{ # for example sake, lets say $f always exists as a file.
my $j = shift;
my $f = shift;
return 0 if !open(FILE, "< $f");
close FILE;
_do_stuff_to_file($f);
return 1;
}
sub _do_stuff_to_file
{
my $f = shift;
open(IN, "< $f");
open(OUT, "> $f.new");
while (<IN>)
{
print OUT;
}
close IN;
close OUT;
}
最佳答案
Perl 中的许多函数使用默认变量 $_
.其中包括 map
和 readline 运算符 <>
.赞 foreach
, map
使循环变量成为它处理的列表中每个元素的别名。发生的事情是这一行:
while (<IN>)
正在分配给
$_
而map
的别名有效。这是使用 $_
的问题之一(或任何其他全局变量)——远距离的奇怪 Action 。如果您打算使用 $_
,先本地化:local $_;
while (<IN>)
...
或者,使用词法变量代替:
while (my $line = <IN>)
关于Perl 默认变量 $_,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3539086/