Course of Raku / Advanced / Containers / Special and dynamic variables 🆕 / Exercises / The topic variable
Solution: The topic variable
Here is a possible solution to the task.
Code
for 'apple', 'fig', 'cherry' {
say "$_ has {.chars} letters";
}🦋 You can find the source code in the file topic-variable.raku.
Output
apple has 5 letters
fig has 3 letters
cherry has 6 lettersComments
A
forloop sets the topic variable$_to each item in turn, so the block runs three times, with$_equal to'apple', then'fig', then'cherry'.Inside the string,
$_interpolates the current word, and the leading-dot.charscall — short for$_.chars— gives its length. Both refer to the same topic, which is why the count always matches the word on the line.