Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Rebinding closures

by diotalevi (Canon)
on Dec 17, 2003 at 00:30 UTC ( [id://315186]=CUFP: print w/replies, xml ) Need Help??

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

Replies are listed 'Best First'.
Re: Rebinding closures
by duff (Parson) on Dec 17, 2003 at 01:36 UTC

    Nifty! But why all of that business with grep to get the odd and even elements of the @replacement_pairs? How about something like this instead:

    sub rebind_closure { my $sub = shift; ref($sub) eq 'CODE' or die "First parameter must be a code ref (cl +osure)"; @_ % 2 or die "Rules must be an even numbered list: @_"; my ($names,@values) = svref_2object( $sub )->PADLIST->ARRAY; my @names = @{$names->object_2svref}; while (($rule,$replacement) = (shift, shift)) { for ( 1 .. $#names ) { next unless rule_matches( $rule, $names[$_] ); my $sigil = substr $names[$_], 0, 1; if ( $sigil eq '$' ) { ${($values[0]->ARRAY)[$_]->object_2svref} = $replaceme +nt; } elsif ( $sigil eq '@' ) { @{($values[0]->ARRAY)[$_]->object_2svref} = @$replacem +ent; } elsif ( $sigil eq '%' ) { %{($values[0]->ARRAY)[$_]->object_2svref} = %$replacem +ent; } elsif ( $sigil eq '*' or $sigil eq '&' ) { warn "$names[$_] cannot be rebound because it is not a + scalar, array or hash"; } else { warn "Unknown sigil $sigil"; } } } }

    As usual, caveat lector, I didn't test this code

      I wanted to be able to access @rules and @replacements by index.

        I saw that but the only place you did it was right at the top of your loop. If you had accessed the rules/replacements by index in more places, it wouldn't have even occurred to me to ask or post an alternative.

Re: Rebinding closures
by jryan (Vicar) on Dec 18, 2003 at 01:12 UTC

    I still don't understand the deal with the grepping. Why not just use a hash?

    sub rebind_closure { my $sub = shift; # Let Perl do the odd-numbered hash error handling for you! my %replacement_pairs = @_; my @rules = keys %replacement_pairs; my @replacements = values %replacement_pairs; # ... }
      Hash keys may only be strings while I wanted my keys to be compiled regex objects and code references. You've just coerced every rule into being strings even where it doesn't make sense.
        I guess you're right; I guess I didn't read carefully enough, and then only saw strings being used in your code. On the other hand, it really doesn't make sense to me to allow any replacements besides strings.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://315186]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (3)
As of 2024-03-29 01:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found