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: workingComments
taskcallslog-itbut never mentions$*prefix. The value still reacheslog-it, because dynamic lookup follows the call stack outward — pasttask— to whoever is on the stack at the time.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.