Wednesday, June 17, 2009

Perl 6 Array Notation

Gabor Szabo uses the following example as his first when talking about arrays in Perl 6:

Now, as I understand it, .perl is supposed to generate the Perl 6 code to create the array, right? So why is it parentheses when he defines the array's contents, but brackets when .perl stringifies it? Are they interchangeable, or is there some special meaning for each?

I tried looking up the answer in S02. As often happens, I learned a lot of interesting points this way, but completely failed to answer my question.


  1. The brackets return an Array object, you can think about it as a reference to an array.

    @a = 1, 2;

    creates a list on the right hand side, and auto-promotes it to an array when assigning to something that starts with an @ sign.

    When you write:

    @a = 1, 2;
    @a = eval @a.perl;

    @a will have one item containing an array object (or array reference, if you want to think in these lines).

    The restriction that Gabor didn't mention was that .perl on an object returns code, that when executed will return the original object in scalar context.

    To reproduce the array, you'd have to write:

    @a = @( eval @a.perl )

  2. So the () versus [] distinction is more or less the same as in Perl 5? Somehow I hadn't expected that!

    Thanks for the explanation.