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

this is quite a dumb, elementary question -- but i can't find the answer

but how do i access the name of the package that the object is?

ie:

package sample; sub new { ... } package main; $a = new sample(); print STDERR $a->NAMEOFPACKAGE;

in the above, i'd like to print "sample", as $a is a sample i know there has to be some attribute that I can't figure out -- and that I don't have to build in an identifier method , I just can't figure it out

Replies are listed 'Best First'.
Re: How do I query the package name of an object?
by Corion (Patriarch) on Jan 30, 2005 at 21:57 UTC

    Simply

    use strict; my $foo = sample->new; print $foo;

    prints out the package name as well as some information uniquely identifying the object you have. If you really only want the package name, the ref function is what you need:

    use strict; my $foo = sample->new; print ref $foo;
Re: How do I query the package name of an object?
by Tanktalus (Canon) on Jan 30, 2005 at 22:02 UTC

    You're looking for ref. It will tell you the package without that extra information that Corion mentions.

    (Elementary ... perhaps. Dumb? No way.)

      Most of the time ref() will do but here is also blessed() in Scalar::Util that does there same as ref() for objects but returns undef for references to unblessed things.

      Condider also if you'd be better off using UNIVERSAL::isa which given an object and a package tells you if the object can be treated as being of the class defined by that package (including any subclasses).

Re: How do I query the package name of an object?
by Frantz (Monk) on Jan 30, 2005 at 22:01 UTC
    In perl objects are references.

    you can use ref function (see perldoc -f ref).

    print STDERR ref($a);
Re: How do I query the package name of an object?
by nmerriweather (Friar) on Jan 30, 2005 at 22:07 UTC

    elementary and dumb!

    I never had to do this before

    ref $this

    is exactly what i needed to know. much thanks to all who posted above and below.

Re: How do I query the package name of an object?
by borisz (Canon) on Jan 30, 2005 at 22:08 UTC
    Use ref or somewhat complicated:
    package sample; sub new { bless {}, shift } package main; my $a = sample->new; use B; print B::class($a);
    Boris

      Update: Remove incorrect reading of Boris' note.

        I just point another way to do it, for fun. I recommend ref for sure. I can not see anything pedantic there. I think you misread my post.
        Boris