To brighten an otherwise boring day, I decided to teach myself a bit about closures.
The example in the Camel Book (3e, P. 253) worked as advertised:
sub newprint { my $x = shift; return sub { my $y = shift; print "$x, $y\n"; }; } $h = newprint("Howdy"); $g = newprint("Greetings"); &$h("world"); &$g("earthlings");
prints "Howdy, world" and "Greetings, earthlings" just fine. But next I tried:
sub make_closures { my $j = 0; my @closures; while (++$j < 7) { push (@closures, sub {print $j, "\n";}); } } foreach my $sub (&make_closures) { &$sub; }
From the above I got
7 7 7 7 7 7
from which I conclude, for lack of a better understanding, that the closure gets the value for $j that $j took on when it went out of scope,
rather than the value of $j when the closure was defined. If correct, that seems a bit counterintuitive. Can anyone shed some light on this behaviour?
In reply to Closure Confusion by Dinosaur
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |