Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending multiple values to an array in Perl6

I am looking for a way to append multiple values to an @array. The documentation points out that there is a method called .append that would do that job. but when I am doing something like this:

my @array = <a b>;
my @values = 1,2,3;
@array.append: @values, 17;

I am getting a nested result:

[a b [1 2 3] 17]
like image 644
Martin Barth Avatar asked Apr 18 '18 08:04

Martin Barth


People also ask

Can you append values to an array?

Append values to the end of an array. Values are appended to a copy of this array. These values are appended to a copy of arr. It must be of the correct shape (the same shape as arr, excluding axis).

How do I append to an array in Perl?

push(@array, element) : add element or elements into the end of the array. $popped = pop(@array) : delete and return the last element of the array. $shifted = shift(@array) : delete and return the first element of the array. unshift(@array) : add element or elements into the beginning of the array.

Can arrays hold multiple values?

An array is a variable that holds multiple values. To use an individual value inside an array, you can use the array access operator. The array access operator is a number value inside square brackets [] . That number provides the index of the array value that you want to use.


1 Answers

You need to slip the array as Perl 6 doesn't auto-slip ("flatten"), except if it's the only iterable in an a argument.

So:

@array.append: @values;      # will slip the array as it's the only parameter
@array.append: @values,17;   # does not slip @values
@array.append: |@values, 17; # will slip the @values into @array

Instead of |@values, you could also slip(@values) or @values.Slip.

like image 65
Elizabeth Mattijsen Avatar answered Oct 07 '22 04:10

Elizabeth Mattijsen