How to specify stride for array in Perl

Viewed 67

For example, how to access the array elements with odd index:

@a=(0,1,2,3,4,5,6,7,8);
print "@a[1..7 with step 2]"; 

The result I want is: 1 3 5 7

2 Answers

In the spirit of your pseudo-code, here is one option using array slices and grep:

my @a = (1, 2, 3, 4, 5, 6, 7, 8);
print @a[ grep { ($_ - 1) % 2 } 0 .. $#a ];

greping in an array slice:

my @a = (1, 2, 3, 4, 5, 6, 7, 8);
print join " ", @a[ grep { ! ($_ % 2) } 0 .. $#a ];
Related