NAME
Sub::Replace - Replace subroutines in packages with controlled effects
VERSION
version 0.2.0
SYNOPSIS
use Sub::Replace;
sub one { say 'One' }
one(); # One
BEGIN { Sub::Replace::sub_replace('one', sub { say 'Uno' }); }
one(); # Uno
BEGIN { Sub::Replace::sub_replace('one', sub { say 'Eins' }); }
one(); # Eins
DESCRIPTION
In Perl, replacing a subroutine in a symbol table is as easy as doing:
*TargetPackage::target_sub = sub { ... };
However that may cause a lot of trouble for compiled code with mentions to \&target_sub
. For example,
sub one { say 'One' }
one();
BEGIN { *one = sub { say 'Uno' }; }
one();
BEGIN { *one = sub { say 'Eins' }; }
one();
will not output
One
Uno
Eins
but
Eins
Eins
Eins
This module provides a sub_replace
function to address that.
FUNCTIONS
Sub::Replace implements the following functions, which are exportable.
sub_replace
$old = Sub::Replace::sub_replace($name, $code);
$old = Sub::Replace::sub_replace($name1, $code1, $name2, $code2);
$old = Sub::Replace::sub_replace(\%subs);
The sub name may be fully qualified (eg. 'TargetPackage::target_sub'
) or not (like 'target_sub'
). In the latter case, the caller package will be used.
The return is a hash ref which maps the fully qualified names into the previously installed subroutines (or undef
if none were there). This is suitable to undo a previous sub_replace
by calling
Sub::Replace::sub_replace($old);
CAVEATS
The same as mentioned in "LIMITATIONS" in Sub::Delete, namely: you may be surprised by taking references to globs in between calls to sub_replace
.
SEE ALSO
AUTHOR
Adriano Ferreira <ferreira@cpan.org>
COPYRIGHT AND LICENSE
This software is copyright (c) 2017-2018 by Adriano Ferreira.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.