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?
POE (Score:1)
or are they exactly the same thing?
Re: (Score:1)
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