In Perl how do you dynamically pick what method to use as a callback?

callback, package, perl, reference

Solution

my $ref = $obj->can('blat');

If $ref is undef, your object can't blat. If $ref is not undef, it's a valid CODE reference to the function in question, suitable for calling "$obj->$ref(@args)".

Problem

In Perl, it's pretty trivial to specify a callback or code reference if its package is known: ``` package Foo; sub foo { print "in foo" } # and then package main; sub baz { my $code = shift; $code->(); } baz( \&Foo::foo ); ``` And this prints `in foo`. Lets say you have an object, ever so trivial, like this: ``` package Foo; sub new { bless {}, shift } sub bar { print "in bar" } sub baz { print "in baz" } ``` You can look up the method using the above way (\&Package:Method) and call it like ``` package main; my $foo = Foo->new(); my $ref = \&Foo::bar; $foo->$ref(); ``` But sometimes (okay, often) you don't know the explicit type. Lets say there's `Foo`, `Bar`, `Baz`, and they all have their own `blat` method. You'd want to get the reference to the appropriate method, based on the object instead of the package. How would you go about that?

Original source