Course of Raku / Advanced / Containers / Special and dynamic variables 🆕 / Exercises
A dynamic variable
Problem
A dynamic variable — one written with the * twigil — is
looked up by searching outward through the call stack, not by lexical
scope. So the value a subroutine sees depends on who called it, which
lets a block run the code it calls under a different identity.
- Declare a dynamic variable
$*userwith the value'guest'. - Write a subroutine
whoamithat printsrunning asfollowed by the current$*user(for example,running as guest). It must read$*userdirectly — it takes no parameters. - Call
whoamionce at the top level: it reportsguest. - Then, inside a block that redeclares
$*useras'admin', call the samewhoamiagain: it now reportsadmin.
Example
The program prints:
running as guest
running as admin