What is block syntax?
The documentation states that each time you see an arrow
->
you are in front of a block syntax, with the definition of a signature.
This applies to iterations and methods that accept code blocks (in Perl 6 a Block is a class by its own, not surprisingly).
But what does it mean? Allow me to try to explain with a simple example: transforming an array thru map
, that as you know, accepts a block.
Let’s start simple:
my @v = 1, 2, 3, 'a', 'b', 'c';
say @v.map: { $_ ~ '-mapped' };
(1-mapped 2-mapped 3-mapped a-mapped b-mapped c-mapped)xo
map
exploits the topic variable
$_
within the block of code.
The above piece of code is totally equivalent to the same, that is its explicit form:
my @v = 1, 2, 3, 'a', 'b', 'c';
say @v.map: -> $_ { $_ ~ '-mapped' };
->
) before the argument list. What it does mean, for short, is that the following piece of code
will work with the signature as input, in a way similar to the definition of a method prototype.
So for instance, you can decide to use another variable instead of the topic one:
my @v = 1, 2, 3, 'a', 'b', 'c';
say @v.map: -> $current { $current ~ '-mapped' };
$current
variable is used as “input” for the block, and that is the way the block syntax work.
But, of course, this opens a wide range of new ways of exploiting things. For instance, if we want to concatenate each pair of elements we can use another signature:
my @v = 1, 2, 3, 'a', 'b', 'c';
say @v.map: -> $one, $two { $one ~ '-mapped-' ~ $two };
(1-mapped-2 3-mapped-a b-mapped-c)
my @v = 1, 2, 3;
say @v.map: -> $one, $two = 4 { $one ~ '-mapped-' ~ $two };
(1-mapped-2 3-mapped-4)
@v
, and placed into $one
and $two
. At the second
iteration only one element is left to be popped from @v
, so only $one
can be populated and therefore $two
assumes the default value specified in the signature.
At glance, signatures applied to blocks can be confusing, especially for the extra arrow, but in the long term being aware of them allows for a more simple code and reduce of complexity.