ref($obj) will only give you the one class $obj was blessed into most recently (since a single object cannot be blessed into more than one class, it only has one class at any time). isa takes an argument, and tells you if $obj is one of those. For example, $obj->isa('thing') will tell you if $obj is blessed as a 'Thing' or any class that inherits from 'Thing'. (as you can see, everything isa->('UNIVERSAL').)

so it depends what you want to know; if you only care what exact object this was blessed as, use ref. If, on the other hand, you want to know if $obj is descended from a particular class, use isa. note that if your code may grow in the future, it may turn out you would prefer to use isa() because it makes your class more subclassable by making the question more general. if i am blessed as a Geek::Perl, and you buy everyone who is a Geek::Programmer a beer, then you should buy me a beer (because Geek::Perl inherits from Geek::Programmer; therefore every Geek::Perl isa Geek::Programmer).

note, too, that often people use isa when what they want to know is can.

for more on isa and can, see Damian Conway's Object Oriented Perl

.

update: if all you're trying to find out is if it is a ref at all, ref is the right thing to use, IMO. Also, if all you're checking for is the builtins, there's no need to deal with subclassing (though tied variables may give you headaches). And, of course, you can't use the $obj->isa('ARRAY') syntax i show above, since HASH, ARRAY, and SCALAR refs aren't objects (until perl6...). In short, having seen your situation, i'd use ref.

.

In reply to Re: UNIVERSAL::isa() vs. ref() by Vynce
in thread UNIVERSAL::isa() vs. ref() by dragonchild

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.