in reply to Re^5: Lexical closures
in thread Lexical closures
In the second snippet, foo() captures $i since $i is a lexical. That means the $i in foo() will always refer to the specific SV associated with $i when foo was compiled. When the loop aliases $i to a different SV, it doesn't affect foo.
use Devel::Peek; my $i; # Lexical variable sub foo { Dump($i); } Dump($i); # SV ... at 0x226048 \ for $i ( 1 ) { # > same foo(); # SV ... at 0x226048 / Dump($i); # SV ... at 0x226d8c }
In the first snippet, there is no closure since $i is not a lexical. That means the foo() will always grab the current value of $main::i.
use Devel::Peek; our $i; # Package variable sub foo { Dump($i); } Dump($i); # SV ... at 0x226d94 for $i ( 1 ) { foo(); # SV ... at 0x226d7c \ same Dump($i); # SV ... at 0x226d7c / }
|
|---|