set_closed_over#

Replace the lexicals that a subroutine closes over with a new set of references.

תקציר#

use PadWalker qw(set_closed_over);
set_closed_over(\&some_sub, \%replacements);

מה מוחזר#

Nothing useful - the function is called for its side effect. For every name in %replacements that matches one of the sub’s captured pad slots, the corresponding slot is replaced by the referent of $replacements{$name}.

דוגמאות#

Swap a closure’s captured variable for a different scalar:

my $n = 1;
my $say = sub { print "$n\n" };
my $other = 42;
set_closed_over($say, { '$n' => \$other });
$say->();                    # 42

Round-trip through closed_over is the idiomatic pattern:

my $refs = closed_over($sub);
$refs->{'$x'} = \my $fresh;
set_closed_over($sub, $refs);

מקרי קצה#

  • Names in %replacements that the sub does not close over are silently ignored.

  • The reftype of each replacement must match the original - scalar for scalar, array for array, and so on. A mismatch croaks with Incorrect reftype for variable NAME (got X expected Y).

  • A non-reference value in %replacements croaks with The variable for NAME is not a reference.

  • XS subs and subs with no padlist are no-ops.

הבדלים מן ה-upstream#

Fully compatible with upstream PadWalker 2.5.

ראו גם#

  • closed_over - read the captures this function writes.

  • peek_sub - broader inspection, read-only.