in reply to Re: understanding closures
in thread understanding closures
a closure is a subroutine which wraps around lexical variables that it references from the surrounding lexical scope which subsequently means that the lexical variables that are referenced are not garbage collected when their immediate scope is exited
This story has a sad end, however. To test my knowledge new-found knowledge, I wrote the following.
I was expecting this to print 0,1,11,12,13 - on the grounds that my two anonymous subs would be saving the same reference to the lexical ($count). But it seems to have merged two of my adds in together!! Help.sub make_two_counters { my $count = 0; return sub{ $count++ }, sub{ $count+=10 } } my ($counter_plus_one, $counter_plus_ten) = make_two_counters(); print $counter_plus_one->() . "\n"; print $counter_plus_one->() . "\n"; print $counter_plus_ten->() . "\n"; print $counter_plus_one->() . "\n"; print $counter_plus_one->() . "\n"; __OUTPUT__ 0 1 12 12 13
BTW: Thanks for all the replies ++
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: understanding closures
by Limbic~Region (Chancellor) on Sep 23, 2005 at 14:04 UTC | |
|
Re^3: understanding closures
by dragonchild (Archbishop) on Sep 23, 2005 at 14:35 UTC | |
|
Re^3: understanding closures
by Anonymous Monk on Sep 23, 2005 at 14:05 UTC | |
by reasonablekeith (Deacon) on Sep 26, 2005 at 08:08 UTC |