|
Posted by Ben Morrow on February 4, 2008, 5:34 pm
Please log in for more thread options
>
> 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
|