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
%replacementsthat 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
%replacementscroaks withThe variable for NAME is not a reference.A second argument that is not a hash reference croaks with
PadWalker::set_closed_over: pad is not a HASH reference.
Differences from upstream#
Upstream PadWalker 2.5 crashes when the first argument is not a code reference, or is a sub with no pad of its own (one implemented natively rather than written in Perl); here both are a no-op.
See also#
closed_over- read the captures this function writes.peek_sub- broader inspection, read-only.