If your array is numeric:

use PDL;
my @old = (1..10);
my @new = pdl(@old)->slice("0:-1:2")->list;

although this is unlikely to be the most efficient way either (due to
the conversion between arrays and piddles).



On Fri, Oct 30, 2009 at 9:05 AM, Mark Fowler <m...@twoshortplanks.com> 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 ];
> }
>
> Or
>
> 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:
>
> i.e.
>
> 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)
>
> e.g.
>
> 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?
>
> Mark.
>
> [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.
>



-- 
http://evolectronica.com - survival of the funkiest

Reply via email to