in reply to sub getting reference to itself : generic way
my $oldsub_ref = \&oldsub; $oldsub_ref->(2); print '-' x 10; *oldsub = \&newsub; $oldsub_ref->(2);
I guess it all depends on what you want here. You are explicitly redefining a subroutine, while you're keeping a code-ref to the old definition.
Note that, if you call the new definition everything works as expected.
If you really want the recursive call from the old defenition to always go to the old definition, you could do this (you already showed this at the end of your post):
So, yes, there is a more or less generic way of getting a reference to the running subroutine: take a reference before the subroutine gets redefined and the symbol table slot gets overwritten. AFAIK there is no way to get at it afterwards.my $sref = \&oldsub; sub oldsub { my $level = shift; print "oldsub [$level]"; $sref->($level - 1) if $level > 0; }
First of all, usually there are no references to the subroutine anymore, and it should be garbage collected, so the old defenition is gone anyway. (This might not happen, as I recall GC-ing subrefs is buggy in most perls)
And assuming somebody keeps a reference around, maybe, by messing with the DB package, you could try and find it, but it would probably not be very efficient, and very ugly.
|
|---|