subroutine's name

N

nazrat

hi,

i have the following setting

*f1 = \&foo;

sub foo {
print 'i am ', (caller(0))[3] , "\n";
}

f1(); # this prints main::foo


is it possible for 'foo' to see its alias being called? (ie. f1() =>
gives main::f1) thanks.
 
B

Ben Morrow

Quoth nazrat said:
i have the following setting

*f1 = \&foo;

sub foo {
print 'i am ', (caller(0))[3] , "\n";
}

f1(); # this prints main::foo

is it possible for 'foo' to see its alias being called? (ie. f1() =>
gives main::f1) thanks.

Not usually, no. Glob aliases point to the same sub, which only has one
name. You can change that name with Sub::Name, but that will change the
name of all aliases to this sub at once.

If you *really* want to do this, you can clone the sub with
Clone::Closure (actually, I think plain Clone will work for subs that
aren't closures), assign that clone a new name, and put that in the
symbol table:

use Clone::Closure qw/clone/;
use Sub::Name qw/subname/;

*f1 = subname f1 => clone \&foo;

but it would probably be better to have foo and f1 call a subordinate
sub with a parameter:

sub _dofoo {
my $name = shift;
warn "I am $name";
}

for my $sub (qw/foo f1/) { # $sub must be lexical
no strict 'refs';
*$sub = sub { _dofoo $sub, @_ };
}

Ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,480
Members
44,900
Latest member
Nell636132

Latest Threads

Top