Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl6 placeholder variable and topic variable

Tags:

raku

There are both placeholder variables and topic variables in Perl 6. For example, the following two statements are the same

say ( $_ * 2 for 3, 9 );        # use topic variables                 
say ( { $^i * 2 } for 3, 9 );   # use placeholder variables

It seems to me, the only benefit one gets from topic variables is saving some keyboard strokes.

My question is: Is there a use case, where a topic variable can be much more convenient than placeholder variables?

like image 947
John Z. Li Avatar asked May 06 '19 09:05

John Z. Li


2 Answers

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.

like image 165
drclaw Avatar answered Oct 31 '22 04:10

drclaw


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.

like image 11
jjmerelo Avatar answered Oct 31 '22 03:10

jjmerelo