Dynamic Variables and Context

Useful built-in dynamics: $*OUT, $*ERR, $*IN, $*CWD, $*TZ, $*SCHEDULER, %*ENV, @*ARGS, $*THREAD, $*TMPDIR, $*EXECUTABLE.

# Dynamic variables (twigil *) are looked up through the CALL STACK, not lexical scope
sub log-msg($msg) { $*LOG-LEVEL >= 1 and say "[{$*REQUEST-ID // '-'}] $msg" }

sub handle-request {
    my $*REQUEST-ID = 'req-42';           # visible to everything called from here
    log-msg('handling');
}
my $*LOG-LEVEL = 1;
handle-request();                         # [req-42] handling

# Temporarily override built-in dynamics
{
    my $*OUT = open('out.txt', :w);       # redirect say/print output in this dynamic scope
    say 'written to file';
    $*OUT.close;
}

# temp: dynamically restore a variable's value at scope exit
our $config = 'production';
sub show-config { say $config }
sub test-mode { temp $config = 'test'; show-config() }
test-mode();                              # test
show-config();                            # production

# CALLER::, OUTER:: and DYNAMIC:: pseudo-packages allow explicit contextual lookups (advanced, rarely needed)