ait has asked for the wisdom of the Perl Monks concerning the following question:
Hello,
Is it OK to use something like (caller(0))[3] to determine current method being executed, or is there a better/easier/safer way using Moose's introspection capabilities? All I need is the simple method name, not even qualified by the namespace.
Thanks,
Alejandro Imass
Re: Moose and caller() for current method
by ambrus (Abbot) on Jul 13, 2010 at 16:54 UTC
|
Why would you need that? Wouldn't you usually already know the name of the method when you define it?
-
If you just plain define the method, then you give it the name:
sub foo { warn "foo" } __PACKAGE__->foo();
-
If you define methods programmatically, you can make them a closure so it knows its name:
for my $n (qw"foo bar") { *$n = sub { warn $n } } __PACKAGE__->foo();
-
If you use AUTOLOAD, the name of the method should be in $AUTOLOAD.
AUTOLOAD { warn $AUTOLOAD } __PACKAGE__->foo();
| [reply] [d/l] [select] |
|
Thanks. The question is: I could hardcode the method name in the code below instead of using caller, or perhaps Moose offers an easier way to determine the method name being executed. The reasons are the same anyone would need caller in the first place. Maybe I'm looking at this from the caller's perpective and it is the called object's method the one who should introspect the caller's object method?
sub hey {
&waka(((caller(0))[3]=~m/::(\w+)$/));
}
sub waka {
my $who = shift;
print "$who called waka\n";
}
| [reply] [d/l] |
|
| [reply] [d/l] |
|
|
|
Re: Moose and caller() for current method
by stvn (Monsignor) on Jul 14, 2010 at 05:10 UTC
|
Moose does not provide any help with getting information out of caller(), that is outside of what I consider Mooses realm of responsibility.
But once you have found the method name, Moose (and the meta layer) can help you find the actual CODE reference, see the Class::MOP::Class docs for more info on that.
| [reply] |
|