in reply to Does Method Exist?

The problem with calling can directly is that you will get an error if you invoke it on something that's not an object:

my $obj = MyClass->new(); # what if it returns undef on error? if ($obj->can('top') # dies!

The traditional way around this is to invoke UNIVERSAL::can (or isa) directly:
    if (UNIVERSAL::can($obj, 'top'))

But this should be avoided. The problem with using these directly is that you don't know if the class author has chosen to implement some specific can or isa functionality. I'm not sure what such functionality might be, mind you, but the principle is that you shouldn't explicitly call a base class's method.

The solution is to use the blessed function from the Scalar::Util module:

# Instead of: if (UNIVERSAL::isa($obj, 'MyClass') # do this: if (blessed $obj && $obj->isa('MyClass')) # Instead of: if (UNIVERSAL::can($obj, 'top') && UNIVERSAL::can($obj->top, 'bottom')) # do this: if (blessed $obj && $obj->can('top') && blessed $obj->top && $obj->top->can('bottom'))

Replies are listed 'Best First'.
Re^2: Does Method Exist?
by ikegami (Patriarch) on Aug 24, 2009 at 16:12 UTC
    If you suspect $obj isn't an object, the following is the suggested solution:
    if (eval { $obj->can($top) })

    However, I don't see any problems with using blessed (aside from being wordier).