If I have an array myarray in Python, I can use the slice notation
myarray[0::2]
to select only the even-indexed elements. For
If you don't mind using an obscure feature of $| you can do this:
{
local $|; # don't mess with global $|
@ar = ( "zero", "one", "two", "three", "four", "five", "six" );
$| = 0;
@even = grep --$|, @ar;
$| = 1;
@odd = grep --$|, @ar;
print "even: @even\\n";
# even: zero two four six
print "odd: @odd\\n";
# odd: one three five
}
or, as a 1 liner:
{ local $|=0; @even = grep --$|, @ar; }
Basically, --$| flip flops between a 0 and 1 value (despite the -- which normally decrements a numeric value), so grep sees a "true" value every other time, thus causing it to return every other item starting with the initial value of $|. Note that you must start with 0 or 1, not some arbitrary index.