in reply to split every other value

This is one way:

my $ra_all = [ [], [] ]; map { push @{$ra_all->[$_ % 2]}, $_ } @array; my @evens = @{$ra_all->[0]}; my @odds = @{$ra_all->[1]};

Regards,

PN5

Replies are listed 'Best First'.
Re^2: split every other value
by Prior Nacre V (Hermit) on Aug 07, 2004 at 00:29 UTC

    And even faster with optimisation:

    my (@evens, @odds); my $ra_all = [ \@evens, \@odds ]; map { push @{$ra_all->[$_ % 2]}, $_ } split /,/, $scalar;

    Regards,

    PN5

      I don't understand the point of the third arrayref. I also find it easier on the eyes with a foreach, but to each his own.

      my ( @evens, @odds ); my @all = ( \@even, \@odd ); push @{ $all[ $_ % 2 ] }, $_ for split /,/, $scalar;

      Brevity, but don't do this at home: you can combine the first two lines into

      my @all = \my ( @evens, @odds );

      Makeshifts last the longest.

        3rd arrayref
        That's there for historical reasons :-)   Actually, this is true, it was there in my first (pre-post) take and it basically got left in. One less dereference is good. Thanks.
        map vs. foreach
        For many years I only ever used foreach but that was because it wasn't available until Perl5. I then didn't use it for much the same reasons you give. About 2-3 years ago I was doing some benchmarking and was amazed at how much faster map was (especially the map BLOCK LIST form) - grep had a similar speed efficiency. I still use foreach; however, usage has made the map format easier on the eyes and I use it on a daily basis without really given it a second thought.
        \my LIST
        I was aware of this. It fails in extraordinarily interesting ways on various 5.6 versions. I now avoid it like the plague!

        So that leaves us (or at least me) with:

        my (@evens, @odds); my @all = (\@evens, \@odds); map { push @{$all[$_ % 2]}, $_ } split /,/, $scalar;

        Regards,

        PN5