in reply to Re: How to tell if a variable is blessed ?
in thread How to tell if a variable is blessed ?

A better answer may be Scalar::Util and blessed.

$scalar = "foo"; $class = blessed $scalar; # undef $ref = []; $class = blessed $ref; # undef $obj = bless [], "Foo"; $class = blessed $obj; # "Foo"

-xdg

Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Replies are listed 'Best First'.
Re^3: How to tell if a variable is blessed ?
by linux454 (Pilgrim) on Mar 02, 2006 at 15:13 UTC
    What does this buy you that a simple ref won't?
    if ( ref($obj) eq "Foo" ) { # We have a Foo object }
    Simple, sweet, and gets the job done. Why over engineer? Of course, if you were already using Scalar::Util for some of its other uses, then I'd say great, but to use a module for something as simple as this, is overcomplicating matters.

      Because if you're merely interested in finding out if the reference is to an instance of some class (as opposed to a hashref, arrayref, ...), what do you put on the other side of the eq? Not to mention the problems with that if you want to gracefully handle subclasses (in which case you really want UNIVERSAL::isa()).

      And ++ to xdg; I'd forgotten all about Scalar::Util::blessed. Much better answer than mine.

      Because the question was how to tell if the reference was blessed, not how to tell if it was blessed into a specific package, ref won't tell you that unless you do a lot of && ref($obj) !~ /HASH/ && ref($obj) !~ /ARRAY/...


      We're not surrounded, we're in a target-rich environment!