http://www.perlmonks.org?node_id=494555


in reply to Re^2: understanding closures
in thread understanding closures

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.

Your closures are correct. However, you're confused about something else. $count++ will return the value of $count, then add 1 to it. $count+=10 will add 10 to count, then return the value of $count.

Try the following:

my $count = 0; sub make_two_counters { return sub{ $count++ }, sub{ $count+=10 } } my ($counter_plus_one, $counter_plus_ten) = make_two_counters(); print $counter_plus_one->() . " ($count)\n"; print $counter_plus_one->() . " ($count)\n"; print $counter_plus_ten->() . " ($count)\n"; print $counter_plus_one->() . " ($count)\n"; print $counter_plus_one->() . " ($count)\n"; __OUTPUT__ 0 (1) 1 (2) 12 (12) 12 (13) 13 (14)

Does that help?


My criteria for good software:
  1. Does it work?
  2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?