in reply to Array Parse

Two solutions come to mind. Either grep as you mentioned:
my $i = 0; my @even = grep $i++ % 2, @array
Or you can build a list containing even numbers and use it to take a slice from the array:
my @idx = map $_ * 2, 0 .. $#array / 2; my @even = @array[@idx];
Here I make a list of consecutive numbers going from 0 to half the value of the biggest array index, then use map to multiply them all by two, giving me a list of all the even indices into the array. Of course you can get rid of the temporary array entirely:
my @even = @array[map $_ * 2, 0 .. $#array / 2];
Since both approaches loop - either over the array or over a list of indices -, I'd probably use the grep solution as it doesn't have to build an extra list, which can consume a lot of memory for large arrays. I showed the index list technique because it is also useful in other cases - f.ex, when you want to access the same elements of several arrays, it's usually the best approach.

Makeshifts last the longest.

Replies are listed 'Best First'.
Re: Re: Array Parse
by rob_au (Abbot) on Jan 19, 2003 at 21:34 UTC
    A more general application of your second technique was posted by Abigail-II in Re: Stepping through an array - This thread also includes a benchmark between these grep and slice techniques.

     

    perl -le 'print+unpack("N",pack("B32","00000000000000000000001000011111"))'

Re: Re: Array Parse
by sauoq (Abbot) on Jan 19, 2003 at 23:12 UTC

    I would not actually recommend this (except for an obfuscation maybe) but I thought it deserved mention anyway:

    my @even = grep --$|, @array;

    -sauoq
    "My two cents aren't worth a dime.";
    
      Obfuscation indeed! What makes this tick? I though the $| had to do with pipes, plumbing and toilets! Please explain?
        Perhaps this helps:
        #perl -e 'print --$| foreach (1..10)' 1010101010

        rdfield

        $! is tied to a variable that is a bit. Therefore it can only be 0 and 1. Set it to a true value and it sets itself to 1. Set it to a false one and it becomes 0. So subtracting 1 from it when it is 0 gives -1 (true) and sets it to 1. Subtracting 1 from 1 gives 0 again.

        When you know how it works, not that complex. But when you first see it it is a bit surprising... (Cue groans.)