in reply to How do closures and variable scope (my,our,local) interact in perl?

Thanx thats fun! 8 )

One can even combine it with loop-var-aliasing!

lanx$ perl -e ' $a='a';$b='b'; my $var; for $var ( $a,$b ) { *$var=sub {print "$var \n" } };$var="x"; a();$b="y";b(); ' a y lanx$ perl -e ' $a='a';$b='b'; for $var ( $a,$b ) { *$var=sub {print "$var \n" } };$var="x"; a();$b="y";b(); ' x x

Obfuscators, here we are! ;-)

Well seriously, I think as a rule of thumb you discovered, that a "localised" lexvar my $var;for $var(){} has the same "closuring"-effects like a  for my $var () {} .

I bet they act exactly the same...

Cheers Rolf

Replies are listed 'Best First'.
Re^2: How do closures and variable scope (my,our,local) interact in perl?
by ikegami (Patriarch) on Jun 16, 2009 at 18:23 UTC

    a "localised" lexvar my var;for $var(){} has the same "closuring"-effects like a for my $var () {} .

    A capture is really a form of aliasing. A slot in the new sub's pad is aliased to the SV of the captured variable. Or three, if another variable already refers to that SV.

    $ perl -MDevel::Peek -e' my $foo = "foo"; my $x; Dump($x); Dump($foo); for $x ($foo) { Dump($x); $f = sub { Dump($x) } } $f->() ' SV = NULL(0x0) at 0x814f69c SV = PV(0x814fb00) at 0x814ecdc SV = PV(0x814fb00) at 0x814ecdc SV = PV(0x814fb00) at 0x814ecdc

    All three names ($foo, loop's $x and sub's $x) all reference (are all aliased to) the same SV (0x814ecdc).