Control flow
for / while / until / loop
FullIterate a list with for, condition-loop with while/until, C-style with loop.
Raku's loops cover three needs: walking a list (for), repeating while a condition holds (while/until), and the explicit three-part C-style loop (loop).
for — iterate a list #
for binds each element to a signature variable. Use -> to name it.
for 1..3 -> $i {
say "i=$i";
}
say "sum ", [+] 1..10;
Output
i=1
i=2
i=3
sum 55Take more than one at a time, or index with .kv:
for <a b c>.kv -> $i, $v {
say "$i: $v";
}
Output
0: a
1: b
2: cwhile / until #
while repeats as long as its condition is true; until is its negation.
my $i = 3;
while $i > 0 {
say $i;
$i--;
}
Output
3
2
1loop — the C-style form #
loop (init; test; step) { } is the explicit three-part loop. A bare loop { } with no parts runs forever (use last to break).
loop (my $j = 0; $j < 3; $j++) {
say $j;
}
Output
0
1
2Notes #
- Loop control:
lastbreaks out,nextskips to the next iteration,redoreruns the current one. foraliases read-write by default when you use<-> $x, so you can modify array elements in place.- The postfix form
say $_ for 1..3is the idiomatic one-liner for simple iteration.