Every other

Abigail abigail at abigail.be
Fri Oct 30 13:26:40 GMT 2009


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"


More information about the london.pm mailing list