In Control flow§
See primary documentation in context for next
The next
command starts the next iteration of the loop. So the code
my @x = 1, 2, 3, 4, 5; for @x -> $x { next if $x == 3; print $x; }
prints "1245".
You can also use next
in a map
: the above example then looks like:
my @x = 1, 2, 3, 4, 5; print @x.map: -> $x { next if $x == 3; $x }
prints "1 2 4 5" because a space is added between entries of a Seq
when it is stringified. Note that that print
was not put inside the block of the map
, as it generally considered bad practice to run a map
for its side-effects (in this case, the print
.
If the NEXT
phaser is present, it runs before the next iteration:
my Int $i = 0; while ($i < 10) { if ($i % 2 == 0) { next; } say "$i is odd."; NEXT { $i++; } } # OUTPUT: «1 is odd.3 is odd.5 is odd.7 is odd.9 is odd.»
In version 6.e.PREVIEW (available as of the 2021.07 Rakudo compiler release), it is also possible to return a value with the next
statement. This is particularly useful when using it in a map
:
my @x = 1, 2, 3, 4, 5; print @x.map: -> $x { next 42 if $x == 3; $x }
prints "1 2 42 4 5".
In a whenever block, next
immediately exits the block for the current value:
react { whenever Supply.interval(1) { next if .is-prime; say $_; done if $_ == 4; } }
prints "0", "1" and "4" - integers from 0 to 4 with primes skipped.
*Since version 6.d, the next
command in a loop that collects its last statement values returns Empty
for the iterations they run on.*