http://qs1969.pair.com?node_id=403522

Or: Hey Rocky, Watch Me Pull A Closure Out Of My Hat

Or: This Is Your Brain, This is Your Brain On Perl

What follows is a (silly) example of how to make methods behave in interesting ways. Or, more accurately, it is an abuse of closures. Anyhow, for those who need brain cells fried, here you go:

use strict; sub prefix_later { my ($just_once,$and_later) = @_; my $ct=0; return sub { my (@args) = shift(); ((!$ct++) ? sub { $just_once->(@args); } : sub { $and_later->(@args); $just_once->(@args); } )->(); } } my $hi_mom = prefix_later( sub { print "hi mom\n"; }, sub { print "this was unneccessary:\n"; } ); $hi_mom->() for (1..3);

Output:

hi mom this was unneccessary: hi mom this was unneccessary: hi mom

You can sort of see how this would be extended to write methods such as postfix_later or do_this_after_five_times or whatever.

How did I come up with this? I was bored. Kids, don't get bored. It's dangerous. (The observant will note the doubly nested closure to seal @args that have could have been eliminated with a shift in array context. Again, I tell you, I was bored)