How do I shorten an array in Perl 6? How do I shorten an array in Perl 6? arrays arrays

How do I shorten an array in Perl 6?


There is a simple way:

my $d = [0..9];$d[5..*] :delete;

That is problematic if the array is an infinite one.

$d.splice(5) also has the same problem.

Your best bet is likely to be $d = [ $d[^5] ] in the average case where you may not know anything about the array, and need a mutable Array.

If you don't need it to be mutable $d = $d[^5] which returns a List may be better.


splice is probably the best choice here, but you can also shorten to five elements using the ^N range constructor shortcut (I call this the "up until" "operator" but I am sure there is a more correct name since it is a constructor of a Range):

> my $d = [ 0 .. 9 ];> $d.elems> 10> $d = [ $d[^5] ][0 1 2 3 4]> $d.elems5> $d[0 1 2 3 4]

"The caret is ... a prefix operator for constructing numeric ranges starting from zero".
                                                                                  (From the Range documentation)

One can argue that perl6 is "perl-ish" in the sense it usually has an explicit version of some operation (using a kind of "predictable" syntax - a method, a routine, and :adverb, etc.) that is understandable if you are not familiar with the language, and then a shortcut-ish variant.

I'm not sure which approach (splice vs. the shortcut vs. using :delete as Brad Gilbert mentions) would have an advantage in speed or memory use. If you run:

perl6 --profile -e 'my $d = [ 0 .. 9 ]; $d=[ $d[^5] ]'perl6 --profile -e 'my $d = [ 0 .. 9 ]; $d.=splice(0, 5);'

you can see a slight difference. The difference might be more significant if you compared with a real program and workload.


Another option is using the xx operator:

my $d = [0..9];$d.pop xx 4;  #-> (9 8 7 6)say $d;       #-> [0 1 2 3 4 5]$d = [0..9];$d.shift xx 5 #-> (0 1 2 3 4)say $d;       #-> [5 6 7 8 9)