Every other

Mike Stok mike at stok.ca
Fri Oct 30 14:08:32 GMT 2009


On Oct 30, 2009, at 9:26 AM, Abigail wrote:

> On Fri, Oct 30, 2009 at 09:05:51AM +0000, Mark Fowler wrote:
>> Hello,
>>
>> I have in the past coded things to only discover later that someone
>> else has already written what I have toiled away on, only better.  So
>> this time, I'm asking the experts[1] first.
>>
>> I have an array in Perl 5 [2].  I want *every* *other* element from
>> it.  There is, of course, more than one way to do it:
>>
>> my @new;
>> foreach (my $i = 0; $i < @old; $i++) {
>>  push @new, $old[ $i ];
>> }
>
>
> Assuming no duplicates or references, and an even sized list:
>
>  my @odds  = keys   %{{@old}};
>  my @evens = values %{{@old}};
>
> Oh, and it won't preserve order either. But at least it's not ugly.
> And it doesn't need additional variables.
>
>
> Abigail  "The blue coat is mine"

Why not something lengthier like

   @evens = @list[ grep {!($_ & 1)} (0 .. $#list) ];

which should preserve order and doesn't care about list size?

Mike

-- 

Mike Stok <mike at stok.ca>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.






More information about the london.pm mailing list