Wrapping a scope
Intricate instruments like *scopes can be quite temparatur sensitive. Wrapping them into some cosy insulator can help. With Perl 6 it is the other way around. When we wrap a Callable
we need to add insulation to guard anything that is in a different scope.
On IRC AndroidKitKat asked a question about formatting Array
-stringification. It was suggested to monkeytype another gist
-method into Array
. He was warned that precompilation would be disabled in this case. A wrapper would avoid this problem. For both solutions the problem of interference with other coders code (in doubt that is you halve a year younger) remains. Luckily we can use dynamic variables to take advantage of stack magic to solve this problem.
Array.^can('gist')[0].wrap(
sub (\a){
print 'wrapped: ';
$*dyn ?? a.join(',') !! nextsame
}
);
my @a = [1,2,3];
{
my $*dyn = True;
say @a;
}
say @a;
# output:
wrapped: 1,2,3
wrapped: [1 2 3]
Dynamic variables don’t really have a scope. They live on the stack and their assigned value travels up the call tree. A wrapper can check if that variable is defined or got a specific value and fall back to the default behaviour by calling nextsame
if need be. Both.wrap
and dynamic variables work across module bounderies. As such we can make the behaviour of our code much more predictable.
This paragraph was meant to wrap things up. But since blogs don’t support dynamic variables I better stop befor I mess something up.
-
April 23, 2019 at 16:272019.16 Easter Down | Weekly changes in and around Perl 6