This allows you to rebind lexicals in a closure. If the closure is current running only the upper-most level binding is replaced. rebind_closure takes a reference to a closure as its first argument and then a list of pairs for replacement.
For each pair the first portion is compared with each bound lexical's name. If it matches then the replacement value is assigned over the original. Your tests may be either code references, compiled regular expressions or strings.
use 5.8.0;
use strict;
use warnings;
use B qw(class svref_2object);
use UNIVERSAL 'isa'; # see UNIVERSAL::isa on CPAN.
=pod
{
my %k = (foo=>'bar');
my $x = 42;
my $y = 32;
my @f = qw(perl monks);
*closure = sub { print "$x $y @f",%k,"\n"; };
}
rebind_closure( \&closure,
'@f' => [ '@f' ],
'$x' => '$x',
'$y' => '$y',
'%k' => { ('%k') x 2 } );
closure();
Prints "$x $y @f%k%k" instead of "42 32 perl monksfoobar"
=cut
sub rebind_closure {
my $sub = shift;
my @replacement_pairs = @_;
if ( @replacement_pairs % 2 ) {
die "Rules must be an even numbered list: @replacement_pairs";
}
my ($names,@values) =
svref_2object( $sub )->PADLIST->ARRAY;
my @names = @{$names->object_2svref};
my @rules = @replacement_pairs[grep !($_ & 1), 0 .. $#replacement_
+pairs];
my @replacements =
@replacement_pairs[grep $_ & 1, 0 .. $#replacement_pairs];
for my $ix ( 0 .. $#rules ) {
my $rule = $rules[$ix];
my $replacement = $replacements[$ix];
for ( 1 .. $#names ) {
if ( rule_matches( $rule, $names[$_] ) ) {
my $sigil = substr $names[$_], 0, 1;
if ( $sigil eq '$' ) {
${($values[0]->ARRAY)[$_]->object_2svref} = $repla
+cement;
} elsif ( $sigil eq '@' ) {
@{($values[0]->ARRAY)[$_]->object_2svref} = @$repl
+acement;
} elsif ( $sigil eq '%' ) {
%{($values[0]->ARRAY)[$_]->object_2svref} = %$repl
+acement;
} elsif ( $sigil eq '*' or
$sigil eq '&' ) {
warn "$names[$_] cannot be rebound because it is n
+ot a scalar, array or hash";
} else {
warn "Unknown sigil $sigil";
}
}
}
}
}
sub rule_matches {
my $rule = shift;
my $name = shift;
return unless $name;
return
!!
isa( $rule, 'CODE' ) ? $rule->( $name ) :
ref( $rule ) ? $name =~ $rule :
$name eq $rule;
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.