in reply to Elegantly Selecting Every 3rd Element in an Array.

my $count = 0; my @every_3rd = grep { ( ++$count % 3 == 0 ) } @array;

-----------------------------------------------------
Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
It's not what you know, but knowing how to find it if you don't know that's important

Replies are listed 'Best First'.
Re: Re: Elegantly Selecting Every 3rd Element in an Array.
by runrig (Abbot) on Sep 29, 2001 at 02:12 UTC
    Without the extra variable declaration:
    my @every_3rd = @array[grep { ! (($_+1) % 3) } 0..$#array];

    Update: Fixed (due to jerrygarciuh's catch). Nothing like untested code. And precedence. (though looking at the precedence table in perlop, it looks like what I had (in jerry's node below) should've worked. Bug? Can someone explain?).

    Another update:tye explains below. Though I think precedence of parens should differ between 'functions' and 'operators'. Oh well...

      Runrig,
      Well, maybe I botched it, but all I did was change @array to my var @a like so:
      my @a=qw(las vegas every saturday night third is my element); my @every_3rd = @a[grep { not ($_+1) % 3 } 0..$#a]; print "@every_3rd";
      and tell it to print and it runs without error but prints nothing.
      ???
      jg

      Ain't no time to hate! Barely time to wait! ~RH
        It prints nothing because you have a precedence problem

        not ($_+1) % 3

        Will always evaluate to false as it is the same as

        (not ($_+1)) % 3

        Adding some parens in the right places

        not (($_+1) % 3)

        Should give the correct result