#!/usr/bin/perl -wl sub gen_counter { my $a = shift; return sub { ++$a }, sub { $a = shift }; } my ($counter, $modifier) = gen_counter(3); print $counter->(); print $counter->(); $modifier->(8); print $counter->(); print $counter->(); # which prints: 4 5 9 10 #### #!/usr/bin/perl -wl sub gen_counter { my $a = shift; return sub { @_ ? $a = shift : ++$a }; } my $counter = gen_counter(3); print $counter->(); print $counter->(); $counter->(8); print $counter->(); print $counter->(); #### sub gen_closure { my ($a, $b, $c) = @_; return sub { if ($some_trigger) { # Calculate new $a, $b, $c based on e.g. the # new @_ and the old $a, $b and $c. return gen_closure($new_a, $new_b, $new_c); } # Do the normal closure action on $a, $b and $c here } }