Course of Raku / Advanced / Containers / Special and dynamic variables 🆕 / Exercises / A dynamic variable
Solution: A dynamic variable
Here is a possible solution to the task.
Code
my $*user = 'guest';
sub whoami {
say "running as $*user";
}
whoami();
{
my $*user = 'admin';
whoami();
}🦋 You can find the source code in the file a-dynamic-variable.raku.
Output
running as guest
running as adminComments
The
*twigil makes$*userdynamic.whoaminever takes it as a parameter — it finds the value by looking outward through the call stack, so the first call reports the defaultguest.The inner block redeclares
$*userasadminfor the duration of that block. The samewhoaminow seesadmin, because dynamic lookup follows whoever is currently on the stack. Overriding a dynamic variable in a scope is how you grant elevated context to everything called from it — without changingwhoamiat all.