Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Moose: get class name

by rootcho (Pilgrim)
on Nov 10, 2010 at 17:17 UTC ( [id://870629]=perlquestion: print w/replies, xml ) Need Help??

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

How to get the class-name in Moose ?

__PACKAGE__ does not work in my case, because I need it inside Role method which could be mixed-in in different classes ?

thanx

PS> silly me of course 'ref' will do it ;) .. thanx guys..

Replies are listed 'Best First'.
Re: Moose: get class name
by Tanktalus (Canon) on Nov 10, 2010 at 17:34 UTC

    Does not ref $self work, just like for regular perl objects?

    sub role_action { my $self = shift; my $obj_type = ref $self; # ... }
    I don't think this is any different. __PACKAGE__ never tells you the class name for the object you're working with, it only gives you the package that you're currently in, which is not the same thing at all if you're in a package that can be inherited from.

    Update: the difference between ref and blessed on $self is probably moot since if $self isn't a reference to a blessed object, either you won't be here or you're probably about to blow up badly anyway. For objects other than $self, there's a bigger difference.

      The difference between ref and Scalar::Util::blessed is subtle and, as you say, won't be any different when operating on a blessed reference.

      blessed is exported as a method, so you can say $moose_object->blessed(), which was why I pointed to that. You can achieve the same with ref($moose_object).

      Having said that, I think I'd prefer:

      $moose_object->blessed()->some_class_method()

      to

      ref($moose_object)->some_class_method()

      rootcho gave no indication of how the class name was to be used, so that may not matter.

      -- Ken

Re: Moose: get class name
by kcott (Archbishop) on Nov 10, 2010 at 17:30 UTC

    Moose exports blessed - way down at the bottom of EXPORTED FUNCTIONS you'll find: "blessed This is the Scalar::Util::blessed function, it is exported here because ...".

    -- Ken

Re: Moose: get class name
by stvn (Monsignor) on Nov 11, 2010 at 16:52 UTC

    ref works just fine, if you want to be all Moosey about it, you can do $self->meta->name.

    -stvn

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://870629]
Approved by Tanktalus
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2024-04-26 01:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found