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):

my $sref = \&oldsub; sub oldsub { my $level = shift; print "oldsub [$level]"; $sref->($level - 1) if $level > 0; }
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.

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.


In reply to Re: sub getting reference to itself : generic way by Joost
in thread sub getting reference to itself : generic way by calin

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.