set_closed_over#

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

Synopsis#

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

What you get back#

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

Examples#

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

Edge cases#

  • 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.

Differences from upstream#

Fully compatible with upstream PadWalker 2.5.

See also#

  • closed_over — read the captures this function writes.

  • peek_sub — broader inspection, read-only.