Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of `@$array` and other constructs

I am still learning Perl 6. Please pardon my ignorance. I am reading the Operators page and I found some unfamiliar constructs at the start of a table:

A   Level   Examples
N   Terms   42 3.14 "eek" qq["foo"] $x :!verbose @$array

I re-read class Array and class Scalar but I am unable to find @$xyz construct in those sections. What do :! and @$ mean? Is there a convenient place that gathers and explains all these symbolic constructs?

Thank you very much !!

like image 879
lisprogtor Avatar asked Jun 22 '17 16:06

lisprogtor


2 Answers

@$foo is short for @($foo), where $foo is an item variable and the @(...) syntax simply calls the .list method on its argument. Both the method and the syntactic form are sometimes called the "list/array contextualizer".

One use for it, is when you want to iterate over an Array stored in an item container. An item container is considered a single item by built-ins such as for loops, whereas calling .list on it returns the plain Array without the surrounding item container (i.e. "forces the value to be interpreted in list context"):

my $foo = [1, 2, 3];

say $foo.perl;       # $[1, 2, 3]
say $foo.list.perl;  # [1, 2, 3]
say @$foo.perl;      # [1, 2, 3]

for $foo { ... }       # One iteration
for $foo.list { ... }  # Three iterations
for @$foo { ... }      # Three iterations (identical to the previous line)

:!foo is short for :foo(False), i.e. a named argument that has the value False:

sub do-something (:$verbose = True) { say $verbose; }

do-something;            # True
do-something :verbose;   # True
do-something :!verbose;  # False

When written in term position but not as an argument of an argument list, it constructs a Pair object:

say (:!verbose);        # verbose => False
like image 160
smls Avatar answered Oct 26 '22 08:10

smls


Using a :verbose parameter would be a good way to set a Bool argument to True with a colon pair. It is equivalent to :verbose(True). :!verbose is just the negation of that, setting it to False, equivalent to :verbose(False).

@$ is a way of using the @ prefix to remove the container from a scalar variable with sigil $.

Consider:

my $x = (1, 2, 3);
.say for $x; 

Output:

(1 2 3)

vs.

my $x = (1, 2, 3);
.say for @$x; 

Output:

1
2
3

Most operators can be searched for directly. These two cases in particular are not individual operators, but cases of using symbols in combination. Those are a little more difficult gather conveniently, but the docs are improving every day.

like image 4
Curt Tilmes Avatar answered Oct 26 '22 09:10

Curt Tilmes