Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

find the package name of an inherited object from inside the parent

by tomgracey (Beadle)
on Jul 07, 2013 at 08:19 UTC ( #1042975=perlquestion: print w/replies, xml ) Need Help??
tomgracey has asked for the wisdom of the Perl Monks concerning the following question:

Hi All

I am sure this is a really simple question but cant figure out how to search for it (I'm not the sharpest stick in the box with Perl anyway tbh). This is a general Perl question, but I am using Moose so a Moose solution would be ok. Suppose I have 2 classes:

package Parent; use Moose; sub who_am_i{ return __PACKAGE__; } package Child; extends 'Parent'; ... some specific Child methods ...

Now if I do

my $child = Child->new; print $child->who_am_i;

I get Parent not Child. (At least this is what seems to happen from my experimentation. Unless I am doing something wrong!)

Is there a way the who_am_i method can be placed in the parent class, but return the package name of the actual initiated class (the child) ?

Sorry for such a basic question!

Replies are listed 'Best First'.
Re: find the package name of an inherited object from inside the parent
by Corion (Pope) on Jul 07, 2013 at 08:33 UTC

    __PACKAGE__ is a constant like __FILE__ and __LINE__. What you might want is ref, which returns the class a reference is blessed into.

    Just be advised that outside of debugging, there is very little you should do based on the class name.

      Oh yeah! ref($self)! That really was a stupid question, apologies...
Re: find the package name of an inherited object from inside the parent
by moritz (Cardinal) on Jul 07, 2013 at 09:15 UTC

    The Mooseish way to get the dynamic class name is $obj->meta->name:

    use 5.010; package Parent; use Moose; sub who_am_I { shift->meta->name }; package Child; use Moose; extends 'Parent'; package main; say Child->new->who_am_I; __END__ Child

    $obj->meta returns the metaclass instance for the object's class, and ->name returns the name (surprise, surprise).

    (excursion: In Perl 6 it works basically the same, except that there is a shortcut for calling methods on the metaclass: say 1.^name says Int).

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1042975]
Approved by Perlbotics
[james28909]: i have discovered hash of arrays

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (9)
As of 2017-04-27 19:19 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (512 votes). Check out past polls.