別の投稿への回答でこのコードを見ました: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が生成されますが、名前の付いたサブシステムは決して新しいスコープに再定義されません(再定義なし)。 – amon
ありがとう、とても助かりました! –