A "classic" example of closures goes something like this:
which generates the output: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;
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")In reply to (tye)Re3: A Real Closure
by tye
in thread Unusual Closure Behaviour
by tachyon
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |