Search code examples
raku

Difference between () and [] in Perl 6


Note This SO should not have the raku tag. It is too obsolete/misleading. The technical problem discussed in the question body no longer applies. The disagreement in the comments about naming/tags no longer applies. I'm leaving it for historical interest only, under the old tag only.


I am learning Perl 6, and had trouble understanding the Perl 6 one-liner below

My Perl 6 is rakudo-star: stable 2014.04 (bottled)

This works fine. The array/list is sorted

[njia@mb-125:~] : perl6 -e 'say [2443,5,33, 90, -9, 2, 764].sort'
-9 2 5 33 90 764 2443

But this does not sort the array/list, if [].sort works why @s.sort does not?

[njia@mb-125:~] : perl6 -e 'my @s = [2443,5,33, 90, -9, 2, 764]; @s.sort.say'
2443 5 33 90 -9 2 764

Change from [] to ()

[njia@mb-125:~] : perl6 -e 'my @s = (2443,5,33,90,-9,2,764); @s.sort.say'
-9 2 5 33 90 764 2443

NOTE the described behavior in this question has changed in the release version of perl6. See response by G. Cito below.


Solution

  • For those who may be confused by this answer, the question is about Perl 6, and none of this applies to Perl 5.

    The statement

    my @s = [2443, 5, 33, 90, -9, 2, 764]
    

    creates an itemised array and assigns it to @s[0], so @s has only a single element and sorting it is pointless.

    However you can say

    @s[0].sort.say
    

    which has the effect you expected