Arrow blocks (lambdas)

Arrow blocks, or pointy blocks, or lambdas define an anonymous sub with only a few characters required to type:

my $cube = -> $x {$x ** 3};
say $cube(3); # 27

Here, the arrow block has its argument $x, whose usage is exactly the same as with regular subs. Likewise in subs, no my keyword is required for declaring the arguments.

Arrow blocks are a common thing to use in loops.

for 1..10 -> $c {
    say $c;
}

An arrow block is being called at each iteration, and the value is passed through the $c variable.

It is possible to have more than one argument in an arrow block. For example, let's convert the two examples above.

First, implement the exponentiation function, which accept both base and exponent values:

my $pow = -> $x, $p {$x ** $p};
say $pow(2, 15); # 32768

Then, modify a loop to take two values at a time:

for 1..10 -> $i, $j {
    say $i + $j;
}

This time, the loop body will be executed five times instead of the previous ten.