Bonus (got the idea by reading tybalt89's version)
sub Invoker::first { shift; &first_callback }
sub Invoker::last { shift; &last_callback }
sub Invoker::AUTOLOAD { -1 }
sub invoker
{
my $name = shift;
Invoker->$name(@_);
}
It looks and kind of quacks like a symbolic ref on the method name, except it works under
strict and
warnings.
Edit: Actually if you ignore the first parameter of the callbacks, you can just use the symbols table as the containing hash and use the method above :)
use strict;
use warnings;
# Callback functions ---------------------------------------
sub first_callback {
my (undef, $z) = @_;
print "in first_callback, z=$z\n";
return 1;
}
sub last_callback {
my (undef, $z) = @_;
print "in last_callback, z=$z\n";
return 2;
}
sub default_callback { -1 }
# Dispatch -------------------------------------------------
%Dispatch:: = ( first => *first_callback,
start => *first_callback,
last => *last_callback,
AUTOLOAD => *default_callback);
sub invoker {
my $name = shift;
Dispatch->$name(@_);
}
# Main program for testing ---------------------------------
for my $name ( qw< first start last fred > ) {
my $rc = invoker( $name, $name . '-arg' );
print "$name: rc=$rc\n";
}
-
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.