Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between () and [] in Perl 6

Tags:

raku

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.

like image 305
Ask and Learn Avatar asked Jun 11 '14 10:06

Ask and Learn


2 Answers

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

like image 65
Borodin Avatar answered Oct 23 '22 12:10

Borodin


I'm going to go out on a limb and refer to some of CPAN's Perl6 documentation where this could be viewed as a list vs. array thing - i.e. a sequence of values versus a sequence of itemized values (see doc.perl6.org).

Certainly perl6 is different enough that it warrants its own tag but it is still perl so it's not surprising that () creates a list and [] creates an anonymous array.

> say [2443, 5, 33, 90, -9, 2, 764].WHAT
(Array)
> say (2443, 5, 33, 90, -9, 2, 764).WHAT
(List)

Since this question was first asked and answered the behavior has changed:

> my @s = [2443, 5, 33, 90, -9, 2, 764]
> @s.sort.say
(-9 2 5 33 90 764 2443)

Note that the output when sorted is a List but otherwise @s is an Array:

> @s.sort.WHAT.say
(List)
> @s.WHAT.say
(Array)
like image 34
G. Cito Avatar answered Oct 23 '22 12:10

G. Cito