[Chicago-talk] Dynamic method call
Steven Lembark
lembark at jeeves.wrkhors.com
Thu Nov 6 19:34:44 CST 2003
> my $sub = $object->can( $method );
> &$sub(@arg);
~~
NO!!! The use of & to make calls is a holdover from Perl4...
Avoid using & for any sort of sub call unless you really
do understand what you are doing with it (at which point
you usually won't do it).
my $method = $item->can( $method_name );
$method->( $item );
is what you are looking for. You want to dereference the
method, NOT call it bypassing prototype def's with the
same @_ as the current call by default.
Note: you can use:
sub dispatch
{
my $item = shift;
my $name = shift;
if( my $sub = $item->can( $name ) )
{
$sub->( $item, @_ )
}
else
{
my $type = ref $item || $item;
die "Bogus dispatch: $type cannot $name";
}
}
Is a fairly general dispatcher:
$foo->dispatch( $methodnames{$inputvalue}, @otherargs );
will get redispatched as necessary. This is nice for
data-driven programming where $inputvalue can be stored
in a config file or input stream and handled by several
objects which can cooperate in dealing with the issue.
--
Steven Lembark 2930 W. Palmer
Workhorse Computing Chicago, IL 60647
+1 888 359 3508
More information about the Chicago-talk
mailing list