別の投稿への回答でこのコードを見ました: 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
同じように、この例でも何が起こっているのかわかりません。誰か説明してくれませんか?
前もって感謝します。