Dinosaur has asked for the wisdom of the Perl Monks concerning the following question:
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?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Closure Confusion
by chromatic (Archbishop) on Oct 16, 2002 at 19:50 UTC | |
|
Re: Closure Confusion
by broquaint (Abbot) on Oct 16, 2002 at 19:55 UTC | |
|
Re: Closure Confusion
by zigdon (Deacon) on Oct 16, 2002 at 19:50 UTC | |
|
Re: Closure Confusion
by BrowserUk (Patriarch) on Oct 16, 2002 at 20:01 UTC | |
|
Re: Closure Confusion
by kabel (Chaplain) on Oct 16, 2002 at 21:04 UTC | |
by Aristotle (Chancellor) on Oct 17, 2002 at 01:54 UTC | |
by kabel (Chaplain) on Oct 17, 2002 at 06:54 UTC | |
by Aristotle (Chancellor) on Oct 17, 2002 at 12:54 UTC | |
by kabel (Chaplain) on Oct 17, 2002 at 14:32 UTC | |
by chromatic (Archbishop) on Oct 16, 2002 at 23:28 UTC | |
|
Re: Closure Confusion
by Dinosaur (Beadle) on Oct 17, 2002 at 14:41 UTC | |
by Aristotle (Chancellor) on Oct 18, 2002 at 12:39 UTC | |
|
Re: Closure Confusion
by Dinosaur (Beadle) on Oct 16, 2002 at 19:54 UTC |