Course of Raku / Advanced / More about built-in types / Quoting constructs 🆕 / Exercises / A closure in a q string

Solution: A closure in a q string

Here is a possible solution to the task.

Code

my $x = 10;
say q:c/$x squared is {$x ** 2}/;

🦋 You can find the source code in the file closure-quote.raku.

Output

$x squared is 100

Comments

  1. The :c (closure) adverb switches on interpolation of embedded { … } code in the otherwise-literal q form. Inside the braces, $x is real code, so {$x ** 2} evaluates to 100.

  2. The $x outside the braces is left exactly as written, because the scalar adverb :s is not enabled. This is the whole point of the per-feature adverbs: you get embedded code without also turning on $-interpolation.

  3. Adverbs can be stacked. Add :s as well, and the leading $x is interpolated too — both features are now on at once:

my $x = 10;
say q:c:s/$x squared is {$x ** 2}/; # 10 squared is 100

Course navigation

A closure in a q string   |   A heredoc