control flow loop

Documentation for control flow loop assembled from the following types:

language documentation Control Flow

From Control Flow

(Control Flow) control flow loop

The loop statement takes three statements in parentheses separated by ; that take the role of initializer, conditional and incrementer. The initializer is executed once and any variable declaration will spill into the surrounding block. The conditional is executed once per iteration and coerced to Bool, if False the loop is stopped. The incrementer is executed once per iteration.

loop (my $i = 0$i < 10$i++{
    say $i;

The infinite loop does not require parentheses.

loop { say 'forever' }

The loop statement may be used to produce values from the result of each run of the attached block if it appears in lists:

(loop ( my $i = 0$i++ < 3;) { $i * 2 }).say;               # OUTPUT: «(2 4 6)␤» 
my @a = (loop ( my $j = 0$j++ < 3;) { $j * 2 }); @a.say;   # OUTPUT: «[2 4 6]␤» 
my @b = do loop ( my $k = 0$k++ < 3;) { $k * 2 }@b.say;  # same thing 

Unlike a for loop, one should not rely on whether returned values are produced lazily, for now. It would probably be best to use eager to guarantee that a loop whose return value may be used actually runs:

sub heads-in-a-row {
    (eager loop (; 2.rand < 1;) { "heads".say })