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"; } );
Re:POE
xsawyerx on 2009-01-13T15:36:19
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 example, consider the following:
my $code_ref = sub { print "hi\n"; };
print "My code reference is $code_ref\n"
. "But when I execute it, it says ";
$code_ref->(); # possible variables too