Course of Raku / Advanced / Containers / Special and dynamic variables 🆕 / Exercises / Override the dynamic

Solution: Override the dynamic

Here is a possible solution to the task.

Code

sub log-it($msg) {
    say "$*prefix: $msg";
}

sub task {
    log-it('working');
}

{
    my $*prefix = 'INFO';
    task();
}

{
    my $*prefix = 'DEBUG';
    task();
}

🦋 You can find the source code in the file override-dynamic.raku.

Output

INFO: working
DEBUG: working

Comments

  1. task calls log-it but never mentions $*prefix. The value still reaches log-it, because dynamic lookup follows the call stack outward — past task — to whoever is on the stack at the time.

  2. The two blocks set different values, so the same task() call produces a different prefix each time. This is what makes dynamic variables useful: context flows into deeply nested code without being threaded through every intermediate routine as an argument.

Course navigation

Override the dynamic   |   The topic variable