control flow for
Documentation for control flow
for assembled from the following types:
From Control Flow
for loop iterates over a list, running the statements inside a block once on each iteration. If the block takes parameters, the elements of the list are provided as arguments.
my = 1..3;for # prints each value contained in @foofor # same thing, because .print implies a $_ argumentfor # prints 42 as many times as @foo has elements
Pointy block syntax or a placeholder may be used to name the parameter, of course.
my = 1..3;for ->for # same thing
Multiple parameters can be declared, in which case the iterator takes as many elements from the list as needed before running the block.
my = 1..3;for .kv -> ,my = <a b c> Z=> 1,2,3;for .kv -> ,for 1, 1.1, 2, 2.1 # says "1 < 1.1" then says "2 < 2.1"
Parameters of a pointy block can have default values, allowing to handle lists with missing elements.
my = 1,2,3,4;for -> , = 'N/A', = 'N/A'# OUTPUT: «1 2 3␤4 N/A N/A␤»
If the postfix form of
for is used a block is not required and the topic is set for the statement list.
say „I $_ butterflies!“ for <♥ ♥ ♥>;# OUTPUT«I ♥ butterflies!␤I ♥ butterflies!␤I ♥ butterflies!␤»
for may be used on lazy lists – it will only take elements from the list when they are needed, so to read a file line by line, you could use:
for .lines ->
Iteration variables are always lexical, so you don't need to use
my to give them the appropriate scope. Also, they are read-only aliases. If you need them to be read-write, use
<-> instead of
->. If you need to make
$_ read-write in a for loop, do so explicitly.
my = 1..3;for <->
A for loop can produce a
List of the values produced by each run of the attached block. To capture these values, put the for loop in parenthesis or assign them to an array:
(for 1, 2, 3 ).say; # says "(2 4 6)"my = do for 1, 2, 3 ; .say; # says "[2 4 6]"my = (for 1, 2, 3 ); .say; # same thing