我在另一篇文章的答案中看到了这一点代码:Why would I use Perl anonymous subroutines instead of a named one?,但无法弄清楚到底发生了什么,所以我想自己运行它。子例程与匿名子例程中的共享变量
sub outer
{
my $a = 123;
sub inner
{
print $a, "\n"; #line 15 (for your reference, all other comments are the OP's)
}
# At this point, $a is 123, so this call should always print 123, right?
inner();
$a = 456;
}
outer(); # prints 123
outer(); # prints 456! Surprise!
在上面的例子中,我收到了警告:“变量$ a不会停留在15行 显然共享的,这就是为什么输出是‘意外’,但我还是不太懂这里发生了什么。
sub outer2
{
my $a = 123;
my $inner = sub
{
print $a, "\n";
};
# At this point, $a is 123, and since the anonymous subrotine
# whose reference is stored in $inner closes over $a in the
# "expected" way...
$inner->();
$a = 456;
}
# ...we see the "expected" results
outer2(); # prints 123
outer2(); # prints 123
本着同样的精神,我不明白是怎么发生的事情或者在这个例子中,可能有人请解释一下吗?
在此先感谢。
“分析”可能是错一个字在这里,但“汇编”似乎稍有不妥太:IIRC,闭包的编译后的代码只是合并到一个新的环境/作用域中,导致一个新的CV,而named subs不会重新映射到一个新的作用域(没有重新定义)。 – amon 2013-05-07 18:05:19
非常感谢,这非常有帮助! – 2013-05-07 18:39:49