Course of Raku / Essentials / Control flow essentials / Loops
for loops
The for loop is a powerful tool to iterate over multiple
elements. For example, let us take a range:
for 1..5 -> $n {
say $n;
}In this program, the variable $n takes the next value
from the range on each iteration. Notice that you do not have to declare
the variable with my explicitly. The block of code is
repeated as many times as the number of elements in the data source. So,
the program prints the numbers line by line:
$ raku t.raku
1
2
3
4
5The program iterates over all the values that the range 1..5 generates. These
are 1, 2, 3, 4, and
5.
Taking more than one value
An interesting feature of Raku is that you can take more than one item in a single iteration. The following program prints two number in a loop:
for 1..6 -> $n, $m {
say "$n and $m";
}The output of this program is the following:
$ raku t.raku
1 and 2
3 and 4
5 and 6Practice
Complete the quiz that covers the contents of this topic.
Course navigation
← Infinite loops |
Understanding the for
loop →
💪 Or jump directly to
the exercises in this section.
Translations of this page: English • Deutsch • Español • Italiano • Latviešu • Nederlands • Български • Русский • Українська