in reply to Re^2: Trying to understand closures
in thread Trying to understand closures

Can you guess what the following snippet prints?
for (1..4) { my $x; print ++$x, " ", \$x, "\n"; sub { $y = $x }; }
And this?
for (1..4) { my $x; print ++$x, " ", \$x, "\n"; sub bob { $y = $x }; }
And now the answer: In the first case there is no closure, so only one $x is created, but in the second case there is a closure so 2 different $xs are created as you can see from the output.

for example:

1 SCALAR(0x8160300)
1 SCALAR(0x8160300)
1 SCALAR(0x8160300)
1 SCALAR(0x8160300)

1 SCALAR(0x81649e8)
1 SCALAR(0x814cd38)
1 SCALAR(0x814cd38)
1 SCALAR(0x814cd38)
-- gam3
A picture is worth a thousand words, but takes 200K.