betterworld has asked for the wisdom of the Perl Monks concerning the following question:
Hello Monks,
I was looking for a way to change the current subroutine name to an arbitrary value (which is unknown at compile time), in order to have caller() return this value.
In particular, it is my ambition to inject a subroutine into an arbitrary package, and that subroutine should use NEXT, as the following code suggests:
Unfortunately, this piece of code does not work as expected, because NEXT will use (caller(1))[3] to determine the calling function, and that won't yield $package . '::function'.use NEXT; no strict 'refs'; *{$package . '::function'} = sub { my $this = shift; # do something $this->NEXT::function(@_); };
You may verify this using the following script:
The output is main::__ANON__, however I'd like it to be testpackage::function.sub printcaller { my $caller = (caller(1))[3]; print "$caller\n"; } my $package = "testpackage"; *{$package.'::function'} = sub { printcaller(); }; testpackage::function();
One possible solution would be eval, but I don't like this much:
sub printcaller { my $caller = (caller(1))[3]; print "$caller\n"; } my $package = 'testpackage'; eval qq{ sub ${package}::function { printcaller(); } }; testpackage::function(); # Output: testpackage::function
I know that I can trick caller() with goto &sub, however, I don't think that this gets me any further.
Does anyone know a solution to my problem?
Thank you very much.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: How to fool caller() / use NEXT within a dynamic sub
by chromatic (Archbishop) on Jul 26, 2005 at 19:57 UTC | |
by betterworld (Curate) on Jul 26, 2005 at 20:35 UTC | |
by xdg (Monsignor) on Jul 26, 2005 at 20:39 UTC | |
by chromatic (Archbishop) on Jul 26, 2005 at 21:29 UTC | |
by betterworld (Curate) on Jul 26, 2005 at 21:08 UTC | |
Re: How to fool caller() / use NEXT within a dynamic sub
by GrandFather (Saint) on Jul 26, 2005 at 19:53 UTC |
Back to
Seekers of Perl Wisdom