Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine if an object implements a method in Perl?

I've got a polymorphic array of objects which implement two (informal) interfaces. I want to be able to differentiate them with reflection along the lines of:

if (hasattr(obj, 'some_method')) {
    # `some_method` is only implemented by one interface.
    # Now I can use the appropriate dispatch semantics.
} else {
    # This must be the other interface.
    # Use the alternative dispatch semantics.
}

Maybe something like this works?:

if (*ref(obj)::'some_method') {
    # ...

I have difficulty telling when the syntax will try to invoke a subroutine and when it will return a subroutine reference. I'm not too familiar with package symbol tables ATM and I'm just trying to hack something out. :-)

Thanks in advance!

like image 286
cdleary Avatar asked Jan 20 '09 10:01

cdleary


1 Answers

use Scalar::Util qw(blessed);
if( blessed($obj) and $obj->can('some_method') ){ 

}

"can" here is a method inherited by all classes from UNIVERSAL . Classes can override this method, but its not a good idea to.

Also, "can" returns a reference to the function, so you can do:

$foo->can('some_method')->( $foo , @args );

or

my $sub = $foo->can('some_method'); 
$foo->$sub( @args ); 
  • Scalar::Util
  • Perl Objects on perldoc.perl.org

Edit Updated Chain Syntax, thanks to Brian Phillips

like image 100
Kent Fredric Avatar answered Oct 19 '22 00:10

Kent Fredric