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();
}
|