Every other

Mark Fowler mark at twoshortplanks.com
Fri Oct 30 09:05:51 GMT 2009


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 ];


my $i;
my @new = grep { $i = !$i } @old;

Or so on.  None of these are particularly readable, or for that
matter, blindly efficient (they still use quite a few ops for such a
simple operation)

What I would prefer is this:

my @new = every_other @old;

Which I guess could be generalised like so:


everyother @array;
everyother @array, $offset;
everyother @array, $offset, $take_how_many;
everyother @array, $offset, $take_how_many, $skip_how_many;

(with the default being everyother @array, 0, 1, 1)


Ideally this would be a utility in List::MoreUtils or suchlike, but
it's not.  Ideally it'd be implemented in C as well as in Perl so that
it doesn't burn ops for such a simple idea.

Before I get going with the coding, does anyone know of anything else
that can do this?


[1] experts on Buffy that is.   Who might also happen to know some Perl.
[2] There's very nice syntax for this in Perl 6, isn't there?  I'm not
using that language yet.

More information about the london.pm mailing list