我在另一个帖子的回答中看到了这段代码:为什么我要使用 Perl 匿名子例程而不是命名的子例程?,但无法弄清楚到底发生了什么,所以我想自己运行它。
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
同样,我也不明白这个例子中发生了什么。有人可以解释一下吗?
提前致谢。