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)


In reply to Functional Programming & method rewriting by SpanishInquisition

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.