In Control flow§
See primary documentation in context for last.
The last
command immediately exits the loop in question.
my @x = 1, 2, 3, 4, 5; for @x -> $x { last if $x == 3; print $x; }
prints "12".
You can also use last
in a map
: the above example then looks like:
my @x = 1, 2, 3, 4, 5; print @x.map: -> $x { last if $x == 3; $x }
prints "1 2" 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 LAST
phaser is present, it runs before exiting the loop:
my Int $i = 1; while ($i < 10) { if ($i % 5 == 0) { last; } LAST { say "The last number was $i."; } NEXT { $i++; } } # OUTPUT: «The last number was 5.»
Since version 6.d, the last
command in a loop that collects its last statement values returns Empty
for the iterations they run on.
In version 6.e.PREVIEW (available as of the 2021.07 Rakudo compiler release), it is also possible to return a value with the last
statement. This is particularly useful when using it in a map
:
my @x = 1, 2, 3, 4, 5; print @x.map: -> $x { last 42 if $x == 3; $x }
print "1 2 42".