Search code examples
arraysrakuscalar

Meaning of `@$array` and other constructs


I am still learning Perl 6. 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?


Solution

  • @$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