SPUG: Getting the name of the method I'm in
David Dyck
dcd at tc.fluke.com
Mon Mar 26 15:20:35 CST 2001
On Mon, 26 Mar 2001, starfire wrote:
> I want to access the name of a method from inside the method, so I can
> write it to the Apache error log. For example:
>
> sub my_method() {
> my ($self, $r) = @_;
> my method_name = ??;
> $r->log_error(ref($self)
> . "::${method_name}: Can't open file $file: $!");
> }
>
> I don't like hard coding it, in case the code is copied and/or the method
> name is changed. $0 won't give me what I want.
>
> Any suggestions?
this should work for you but it includes the package name:
my $method_name = (caller(0))[3]; # package and subroutine name
$method_name =~ s/^.*:://; # strip off package name
perl -le 'package mypackage;sub y{ print +(caller(0))[3]; } &y'
prints
mypackage::y
also see perldata, as you may be able to use __PACKAGE__
instead of ref($self)
The special literals __FILE__, __LINE__, and __PACKAGE__
represent the current filename, line number, and package name at that
point in your program. They may be used only as separate tokens; they
will not be interpolated into strings. If there is no current package
(due to an empty C<package;> directive), __PACKAGE__ is the undefined
value.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
POST TO: spug-list at pm.org PROBLEMS: owner-spug-list at pm.org
Subscriptions; Email to majordomo at pm.org: ACTION LIST EMAIL
Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
For daily traffic, use spug-list for LIST ; for weekly, spug-list-digest
Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/
More information about the spug-list
mailing list