monkeyhelper has asked for the wisdom of the Perl Monks concerning the following question:

I have a object that I'd like to retrieve the classname for :

print Dumper $object

gives:

$VAR1 = bless( {}, 'Some::Object' );

I'd like to be able to retrieve 'Some::Object' as a string to operate on. I'm sure the answer must be simple but I've not been able to find a way to do it other than add a getter to the class to store the information, which isn't particularly elegant as the information is already there.

Replies are listed 'Best First'.
Re: Retrieving classname from an object
by chromatic (Archbishop) on Jul 10, 2006 at 23:09 UTC
Re: Retrieving classname from an object
by runrig (Abbot) on Jul 10, 2006 at 23:10 UTC
    You can get it from ref() or get it more directly/accurately from Scalar::Util::blessed(). (ref, e.g., will return 'ARRAY' for an unblessed array reference or 'HASH' for an unblessed hash reference, while blessed will only return results for blessed references).

    Updated.

      ref, e.g., will return 'ARRAY' for an unblessed array reference

      Which is amusing:

      { package ARRAY; sub new { return bless \shift; } } print join ' ', ref \@{[]}, ref ARRAY->new ("something"), "\n"; __END__ ARRAY ARRAY

      --
      David Serrano

      I had a look at ref and it didn't seem to provide this info - Do you have an example (out of curiosity) ? I'll use Scalar::Util for now. Thanks for the help.
        my $class = ref $object;
Re: Retrieving classname from an object
by diotalevi (Canon) on Jul 11, 2006 at 02:34 UTC

    Why are you asking for an object's class? Typically a person needs this when they're checking whether an object is of a certain kind so they can either know what it's capable of or to somehow make a decision. If that's your purpose then you've asked for the wrong piece of information. If you want to know whether an object is of a particular kind, use $obj->isa( $your_class ). That will respect any normal object oriented ISA relationships. If you want to know whether an object is capable of doing something you can use the $obj->can( $method_name ) to ask whether it has a method of a particular name. You'll find these documented in the normal documentation like perlobj.

    if ( ref( $obj ) eq 'Foo::Bar' ) { # This is generally wrong } use Scalar::Util 'blessed'; if ( blessed( $obj ) and $obj->can( $some_method ) ) { # We asked if the object could do something. We win. OO inheritanc +e was respected and we played by the rules. } if ( blessed( $obj ) and $obj->isa( 'Some::Object' ) ) { # This is close to your original and is slightly deprecated but al +so respects OO inheritance. }

    ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊