Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

(tye)Re3: A Real Closure

by tye (Sage)
on Jul 13, 2001 at 02:58 UTC ( #96224=note: print w/ replies, xml ) Need Help??

in reply to Re: (tye)Re2: A Real Closure
in thread Unusual Closure Behaviour

A "classic" example of closures goes something like this:

sub generateSequencer { my( $start, $inc )= @_; $start -= $inc; return sub { return $start += $inc; }; } my $countByTwos= generateSequencer( 0, 2 ); print $countByTwos->(), $/ for 1..3; my $countByThrees= generateSequencer( 1, 3 ); print $countByTwos->(), " ", $countByThrees->(), $/ for 1..4;
which generates the output:
0 2 4 6 1 8 4 10 7 12 10

So we have $countByTwos and $countByThrees are both references to the code: sub { return $start += $inc; };
except that the code reference $countByTwos has hidden inside of it references to the $start and $inc that were created when generateSequencer was called the first time while $countByThrees has hidden inside of it references to the other $start and $inc (that were created when generateSequencer was called the second time).

So both of those code references end up using the same code, but they each end up using different variables even though we don't pass any variables at all as arguments in here: print $countByTwos->(), " ", $countByThrees->(), $/

        - tye (but my friends call me "Tye")

Comment on (tye)Re3: A Real Closure
Select or Download Code

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://96224]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2015-10-10 11:55 GMT
Find Nodes?
    Voting Booth?

    Does Humor Belong in Programming?

    Results (255 votes), past polls