πŸ“˜ Taking every second element using Perl 6

Form a new array by picking every second element from the original array.

There is an array of numbers, and the task is to pick every second element and put them into a new array.

Prepare the test data:

my @data = 20..30;

Here is a possible solution:

my @selected = @data[1, 3 ... *];
say @selected;

This program prints the following values:

[21 23 25 27 29]

We are using a slice to provide the needed indices within the pair of square brackets. To make a slice, just list more than one element inside the brackets, for example:

say @data[2, 3, 5]; # (22 23 25)

To select every second element, a sequenceΒ 1, 3...* is created. TheΒ ... sequence operator creates a sequence based on the example list provided on its left side. The two numbers, 1 and 3, provide a pattern for the arithmetic progression; thus, every element is calculated asΒ xn = x(n-1) + 2.

The star at the right end of the sequence ensures that the sequence is generated until the whole array has been looked up. Using theΒ * is a very PerlΒ 6-ish way to ask the compiler to do the right job for you (theΒ Do What I Mean, or DWIM, principle).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s