Don't "embed" the subroutine in the first place, but make it a parameter (or a global variable if you must).

I assume you have something like this:

sub foo { print 'Foo!' }; sub bar { my( $output ) = @_; $output->(); }; bar( \&foo );

If you want to change what bar() does, change its calling site:

sub foo1 { print 'Foo! One' }; sub foo2 { print 'Foo! Two' }; bar( \&foo1 ); bar( \&foo2 );

If you really, really want the action at a distance, use a global variable:

sub foo1 { print 'Foo! One' }; sub foo2 { print 'Foo! Two' }; use vars '$output'; sub bar { $output->(); }; local $output = \&foo1; bar(); local $output = \&foo2; bar();

If you really, really, really feel that what you want to do is to override foo on a completely global level, you can do the following, but know that I consider this a practice last resort which might be incredibly useful but if you control the source code of foo and bar, while cute this practice will lead to hard to understand control flow:

sub foo { print 'Foo!' }; sub bar { foo(); }; bar(); { local *foo = sub { print 'Foo! reloaded!'; }; bar(); }

In reply to Re: Redefine the sub of a subref? by Corion
in thread Redefine the sub of a subref? by aplonis

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.