perl6 placeholder variable and topic variable

There are several topic variables, one for each sigil: $, @, %_ and even &_ (yep, routines are first-class citizens in Perl6). To a certain point, you can also use Whatever (*) and create a WhateverCode in a expression, saving even more typing (look, ma! No curly braces!).

You can use the array form for several variables:

my &block = { sum @_ }; say block( 2,3 )

But the main problem they have is that they are single variables, unable to reflect the complexity of block calls. The code above can be rewritten using placeholder variables like this:

my &block = { $^a + $^b }; say block( 2,3 )

But imagine you've got some non-commutative thing in your hands. Like here:

my &block = { @_[1] %% @_[0] }; say block( 3, 9 )

That becomes clumsy and less expressive than

my &block = { $^divi %% $^divd }; say block( 3, 9 ); # OUTPUT: «True␤»

The trick being here that the placeholder variables get assigned in alphabetical order, with divd being before divi, and divi being short for divisible and divd for divided (which you chould have used if you wanted).

At the end of the day, there are many ways to do it. You can use whichever you want.


The topic can have method calls on it:

say ( .rand for 3,9);

Compared to a placeholder:

say ( {$^i.rand} for 3,9);

Saves on typing a variable name and the curly braces for the block.

Also the topic variable is the whole point of the given block to my understanding:

my @anArrayWithALongName=[1,2,3];

@anArrayWithALongName[1].say;
@anArrayWithALongName[1].sqrt;

#OR

given @anArrayWithALongName[1] {
    .say;
    .sqrt;
}

That's a lot less typing when there are a lot of operations on the same variable.

Tags:

Raku