Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

xsawyerx (8978)

xsawyerx
  (email not shown publicly)

Journal of xsawyerx (8978)

Sunday January 11, 2009
05:15 AM

POE Explained... sort of. part 1 - callbacks!

[ #38257 ]
I'll be trying to explain POE with a series of articles that cover what you need to know to understand POE and how POE works. The idea is to write a series of short articles in order to make it easier to read and understand and not be overwhelmed with information. Hopefully it will help some people.
When I'll finish writing it, I'll send it to the POE team to perhaps publish on poe.perl.org.

Callbacks

A callback is when you provide a code reference (anonymous subroutine or reference to an existing one) and then use the reference to call that subroutine at a later time. A common usage is dispatch tables. Example:

my %dispatch = (
    say => sub { print $_[0] . "\n"; }
);
$dispatch{'say'}->("yo!");

When just declaring the subroutine, it does not get executed, but rather stored as a reference to some anonymous subroutine.Then later, I can call it, and even provide it with parameters. I could also send an anonymous subroutine to some function which would run it, as such:

sub omg {
    my $code_ref = shift;
    $code_ref && $code_ref->();
    print "what do I do now?\n";
    return 0; # always return
}

my $code_ref = sub {
    print "AHHHH!\n";
}

omg($code_ref);
omg(
    sub {
        print "Okay, I calmed down...\n";
    }
);

Any questions?

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • how are callbacks different from first class functions?
    or are they exactly the same thing?
    • I haven't heard the expression first class functions till now. From what I checked on Wikipedia, it seems like the exact same thing.

      You store code to be run in a data structure and execute it only when accessing that data structure.
      That data structure could be any variable (as an item in a list, as a scalar or as the entry inside a rather elaborate hash structure) and the code you're storing is strictly not code, but a reference to code. When it's accessed, it executes the code in that reference.

      For ex