Reputation: 25117
How could I cut off an array or an array-reference in Perl 6?
In Perl 5, I can do this:
my $d = [0 .. 9];
$#$d = 4;
In Perl 6, I get an error if I try this:
my $d = [0 .. 9];
$d.end = 4; # Cannot modify an immutable Int
This works, but it looks less beautiful than the Perl 5 way and may be expensive:
$d.=splice(0, 5);
Upvotes: 8
Views: 484
Reputation: 70
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)
Upvotes: 2
Reputation: 6378
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.elems
5
> $d
[0 1 2 3 4]
"The caret is ... a prefix operator for constructing numeric ranges starting from zero".
(From theRange
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.
Upvotes: 6
Reputation: 34120
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.
Upvotes: 13