In Perl 6, interestingly, it is possible to execute part of the body only once. For example, in the next loop, there should be four iterations done, but the first message will be printed only once:
for 1, 2, 3, 4 {
once {
say 'Looping from 1 to 4';
}
say "Current value is $_";
}
The preceding code prints the following output:
Looping from 1 to 4
Current value is 1
Current value is 2
Current value is 3
Current value is 4
The block of code after the once keyword was executed only once.
This also works with loops of other types, for example, with the loop cycle. Considering the following code snippet:
loop (my $c = 1; $c != 5; $c++) {
once say 'Looping from 1 to 4';
say "Current value is $c";
}
Notice that no curly braces are needed if you only have a single instruction to be executed once.
The once keyword...