in reply to How to tell if a variable is blessed ?

See ref. And variables aren't blessed, referenced values (SV*, AV*, et al) are blessed (not the variable containing the reference or the reference itself; it's the thing that is blessed or not, not the pointer to the thing).

Replies are listed 'Best First'.
Re^2: How to tell if a variable is blessed ?
by xdg (Monsignor) on Mar 02, 2006 at 14:57 UTC

    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.

      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!
Re^2: How to tell if a variable is blessed ?
by jeanluca (Deacon) on Mar 02, 2006 at 14:51 UTC
    I tried to do it with ref, but than the only solution I can think of is:
    if ( ref($a) && ref($a) !~ /HASH|ARRAY/ ) { $a->blabla(...) ; }
    According to the answers to this post I assume this is the answer ?!

    Thanks
    Luca