Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple components in an array slice - equivalent to perl5: @a[0..1,3]

Tags:

slice

raku

Very basic question but I can't seem to find anything about multiple ranges in the docs.

How do you select multiple ranges from a perl6 array?

my @a = "a","b","c","d";

@a[0..1,3] # expecting array with a, b & d as p5

This seems to return a sort of nested list, what's the Perl 6 syntax to acheive the result this would yeild in Perl 5 (i.e an array with a, b & d)?

like image 320
Richard J. Acton Avatar asked Oct 03 '18 10:10

Richard J. Acton


2 Answers

Your question is a little confusing, but assuming you've just got typos or whatever, I'll try to guess what you are asking.

This makes a simple array:

> my @a = "a", "b', "c", "d";
[a b c d]

This makes an anonymous array of a Range from 0..1 and a 3:

> @[0..1,3];
[0..1 3]

If you want it to pull values out of the @a array, you have to refer to it:

> @a[0..1,3];
((a b) d)

pulls the bits you asked for from @a -- The first element is the 0..1 parts of @a, (a,b) -- (Not sure why you want to see c in here..)

That's the nested list -- the two bits you asked for include the list in the first field, and the value d you asked for in the second field.

If you want it flattened instead of nested, you can use .flat:

> @a[0..1,3].flat;
(a b d)
like image 81
Curt Tilmes Avatar answered Nov 14 '22 07:11

Curt Tilmes


In Raku (formerly known as Perl 6), 0..1 results in a single item, which is a range. In Perl 5, 0..1 immediately expands into two numbers.

One of my most common mistakes in Raku is forgetting to flatten things. The upside is that in Raku, we basically get the equivalent of Perl 5 references for free, which eliminates a lot of messy referencing and dereferencing.

like image 5
Christopher Bottoms Avatar answered Nov 14 '22 06:11

Christopher Bottoms