in reply to Quicly extracting odd index elements in the array with grep

grep and map:

use warnings; use strict; my @arr = (0,3,4,5,8,10,12,15); # # # # my @var = map {$arr[$_]} grep {$_ & 1} 1..$#arr; print "@var";

Prints:

3 5 10 15

DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: Quicly extracting odd index elements in the array with grep
by ikegami (Patriarch) on Aug 10, 2006 at 04:53 UTC

    Here are some more efficient variants, if dealing with long lists. The first uses only half as much memory (and is probably faster), and the second uses no extra memory (and is probably the fastestand is still quite fast). The difference should be inconsequential for short lists.

    my @var = map { $arr[$_*2+1] } 0..int(@arr/2)-1;
    my @var; push(@var, $arr[$_*2+1]) for 0..int(@arr/2)-1;

    Update: For speed considerations when dealing with long lists, refer to GrandFather's post.

Re^2: Quicly extracting odd index elements in the array with grep
by bobf (Monsignor) on Aug 10, 2006 at 04:56 UTC

    You can eliminate the map by taking a slice:

    my @var = @arr[ grep {$_ & 1} 1..$#arr ];

Re^2: Quicly extracting odd index elements in the array with grep
by Anonymous Monk on Aug 10, 2006 at 05:41 UTC
    GrandFather

    can you explain me the following line. I am not able to understand what is that doing exactly.
    my @var = map {$arr$_} grep {$_ & 1} 1..$#arr;

      Read the comments from the bottom up.
      my @var = # Store the elements in @var. map { $arr[$_] } # Get the elements at the remaining indexes. grep { $_ & 1 } # Filter out the even indexes. 0..$#arr; # Create a list of @arr's indexes.