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";
}