in reply to name of executing sub?

Caller works well enough except for AUTOLOAD.

#!/usr/bin/env perl use strict; use warnings; sub foo { my $name = (caller(0))[3]; my $caller = (caller(1))[3]; if ( defined $caller ) { print "My name is $name and I was called by $caller.\n"; } else { print "My name is $name.\n"; } } sub bar { my $name = (caller(0))[3]; my $caller = (caller(1))[3]; if ( defined $caller ) { print "My name is $name and I was called by $caller.\n"; } else { print "My name is $name.\n"; } foo(); baz(); } sub AUTOLOAD { my $name = (caller(0))[3]; my $called = our $AUTOLOAD; my $caller = (caller(1))[3]; if ( defined $caller ) { print "My name is $name and I was called as $called by $caller +.\n"; } else { print "My name is $name and I was called as $called.\n"; } } foo(); bar(); baz(); __END__ My name is main::foo. My name is main::bar. My name is main::foo and I was called by main::bar. My name is main::AUTOLOAD and I was called as main::baz by main::bar. My name is main::AUTOLOAD and I was called as main::baz.

Updated to show who called (if applicable).

Replies are listed 'Best First'.
Re^2: name of executing sub?
by tobyink (Canon) on Jan 11, 2014 at 00:11 UTC

    This is why I think that the best way of implementing AUTOLOAD is something like this:

    use Sub::Name; sub AUTOLOAD { my ($name) = (our $AUTOLOAD =~ /(\w+)$/); my $func = subname $name => sub { ...; # this is where the work happens }; no strict 'refs'; *$name = $func; goto $func; }

    What this means is that the first time an autoloaded function is called, AUTOLOAD creates the function as a coderef, and then installs that into the symbol table, so that the next time the same named function is called, no AUTOLOAD needs to happen.

    And it fixes caller, and stuff that relies on caller like Carp::confess.

    use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name
Re^2: name of executing sub?
by arley_ge (Initiate) on Jan 10, 2014 at 19:22 UTC
    Outstanding!

    The AUTOLOAD part is beyond my current understanding but the examples enlightened me to exactly what I needed!