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'))


In reply to Re: Does Method Exist? by Sue D. Nymme
in thread Does Method Exist? by Aric

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.