Course of Raku / Essentials / Loops

Topic variable

$_ is a special variable called the topic variable.

Consider the loop over a range:

for 1..5 -> $n {
    say $n;
}

The variable $n can be omitted, in which case it will be replaced with an automatically generated variable $_. The program is equivalent to the following:

for 1..5 {
    say $_;
}

As you remember, it is possible to use say as a method:

for 1..5 {
    $_.say;
}

Calling methods on $_ does not require mentioning the variable itself. So, our loop can be simplified further:

for 1..5 {
    .say;
}

Course navigation

Loops / for loops   |   Loops / Postfix form of for


💪 Or jump directly to the exercises to this section.