in reply to Re: alternate array elements
in thread alternate array elements

With the advent of the new state key word in 5.10. I would think this would be the best solution today.
my @odd = grep {state $i=1; $i++ % 2} qw{a 1 b 2 c 3}; my @even = grep {state $i=0; $i++ % 2} qw{a 1 b 2 c 3};
Example
perl -e 'use v5.10; my @odd = grep {state $i=1; $i++ % 2} qw{a 1 b 2 +c 3}; say @odd;'

Replies are listed 'Best First'.
Re^3: alternate array elements
by LanX (Saint) on May 12, 2023 at 21:19 UTC
    BTW: for one-liners you can use global vars like $a or $b without declaration, even when strict.

    C:\>perl -e"print grep {++$a % 2} qw{a 1 b 2 c 3}" abc

    Though their values will leak into the outer scope, so state is better for longer scripts.

    FWIW: I always thought that an automatic loop-count variable $c or $^c would come very handy inside grep-like constructs.

    Cheers Rolf
    (addicted to the 𐍀𐌴𐍂𐌻 Programming Language :)
    Wikisyntax for the Monastery