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 ++
In reply to Re^2: understanding closures
by reasonablekeith
in thread understanding closures
by reasonablekeith
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |