Raku by Example: Loops

There are several types of looping constructs in Raku.

for

my @numbers = 2, 4, 6;

# Loop over an array. Unless stated explicitly,
# elements are stored in the topic variable, $_.
for @numbers {
    print $_;
}

# Loop over an array with explicit elements by using
# a pointy block (->). The elements are read only.
for @numbers -> $number {
    print $number;
}

# Loop over an array with explicit elements by using
# a doubly pointy block (<->). The elements are read-write.
for @numbers <-> $number {
    $number = $number * 2;
}
say "Numbers: @numbers[]"; # Elements have been mutated.

# Looping over a range. This includes both endpoints.
for 0..3 -> $i {
    print $i; 
}
say "";

# To exclude either of them, use $s ^.. $e or $s ..^ $e.
# To exclude both, just use $s ^..^ $e. Thus:
# 1 ^.. 5  is equivalent to 2..5
# 1 ..^ 5  is equivalent to 1..4
# 1 ^..^ 5 is equivalent to 2..4

# For a range from 0 up to N (exclusive), use: ^N.
# For example:
for ^6 {
    print $_;
}
say "";
$ perl6 for.p6
246
246
Numbers: 4 8 12
0123
01235

while

say "while loop:";
my $i = 0;
while $i < 4 {
    say "$i: ", $i * $i;
    $i++;
}

# A `while` loop iterates while a condition is met. To iterate while
# a condition hasn't been met, you may want to use the `until` loop:

say "until loop:";
my $j = 0;
until $j == 4 {
    say "$j: ", $j * $j;
    $j++;
}
$ perl6 while.p6
while loop:
0: 0
1: 1
2: 4
3: 9
until loop:
0: 0
1: 1
2: 4
3: 9

loop

# This is Raku's C-style loop.
# Do this three times.
loop (my $i = 1; $i <= 3; $i++) {
    say $i;
}

# Without arguments, it's an infinite loop.
# Use some condition to stop it.
my $j = 0;
loop {
    say $j * $j;
    last if $j == 2;
    $j += 1;
}
$ perl6 loop.p6
1
2
3
0
1
8

next, last and redo

# next - starts the next iteration of a loop.
say 'next:';
for 1..6 -> $n {
    next if $n %% 2;
    print $n;
}
say "";

# last - immediately exits a loop.
say 'last:';
for 1..9 -> $n {
    last if $n > 6;
    print $n;
}
say "";

# redo - restarts the loop block without evaluating the conditional again.
say 'redo:';
loop {
    my $input = prompt 'Enter a number: '; # Ask for a number.
    redo unless $input ~~ /\d+/;           # Redo if not a number.
    last;                                  # Exit loop if a number was entered.
}
$ perl6 loop_control.p6
next:
135
last:
123456
redo:
Enter a number: one
Enter a number: 12

For additional information, go to https://docs.perl6.org/language/control.

Back to main