๐Ÿ“˜ Anonymous code blocks in Perl 6

Perl 6 introduces the concept of so-called pointy blocks (or pointy arrow blocks). These are anonymous closure blocks, which return a reference to the function and can take arguments.

The syntax of defining pointy blocks is an arrow -> followed by the argument list and a block of code.

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

Here, the block {$x ** 3}, which takes one argument $x, is created first. Then, it is called using a variable $cube as a reference to the function: $cube(3).

Pointy blocks are quite handy in loops.

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

The for loop takes two arguments: the range 1..10 and the block of code with the argument $c. The whole construction looks like syntactic sugar for loops.

There can be more than one argument. In that case, list them all after an arrow.

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

The same works with loops and with other Perl elements where you need passing anonymous code blocks.

for 0..9 -> $i, $j {
ย ย ย  say $i + $j;
}

In a loop iteration, two values from the list are consumed each time. So, the loop iterates five times and prints the sum of the pairs of numbers: 1, 5, 9, 13 and 17.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s