in reply to alternate array elements

$ perl -E 'say grep {++$i %2} <a b c d e f g>' aceg $ perl -E 'say grep {$i++ %2} <a b c d e f g>' bdf

They only nasty thing about this solution is that it requires a variable (here $i) in the outer scope

A working Perl 6 solution:

$ perl6 -e 'my @a = "a".."g"; say @a[0, *+2 ... +@a]' aceg

An idiomatic Perl 6 solution (but not yet implemented in Rakudo):

@a[0, *+2 ... *]

Another working Perl 6 solution, which is a variation of the grep theme but without the need of an external variable:

say <a b c d e f g>.pairs.grep({.key !% 2})>>.value

(Updated: Added Perl 6 examples)

Perl 6 - links to (nearly) everything that is Perl 6.

Replies are listed 'Best First'.
Re^2: alternate array elements
by mrdvt92 (Acolyte) on May 12, 2023 at 17:39 UTC
    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;'
      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