Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-19 05:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found