Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re^3: understanding closures

by dragonchild (Archbishop)
on Sep 23, 2005 at 14:35 UTC ( #494555=note: print w/replies, xml ) Need Help??

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?

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://494555]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2018-06-22 06:27 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (121 votes). Check out past polls.