in reply to Fastest way to grep multiple time on some array

From the description, it sounds like you're taking a big array and trying to split it into a number of smaller arrays. I'd have expected the most efficient approach to be to do everything in a single pass, rather than looping over the array several times.

That is to say, instead of

my @As = grep { /A/ } @bigarray; my @Bs = grep { /B/ } @bigarray; my @Cs = grep { /C/ } @bigarray;

I would write

my (@As, @Bs, @Cs); for my $item (@bigarray) { if ($item =~ /A/) { push @As, $item } elsif ($item =~ /B/) { push @Bs, $item } elsif ($item =~ /C/) { push @Cs, $item } }

Replies are listed 'Best First'.
Re^2: Fastest way to grep multiple time on some array
by holli (Abbot) on Feb 19, 2009 at 11:03 UTC
    or even
    my %H; for my $item (@bigarray) { push @{$H{$1}}, $item if ($item =~ /(A|B|C)/); }


    holli

    When you're up to your ass in alligators, it's difficult to remember that your original purpose was to drain the swamp.
      I think this would fail if one of the items in bigarray was "AB", as it would only add this item to $H{"A"} and not $H{"B"}.

      Alas we don't know for sure whether this would be a problem for the OP or not, but re-reading the post suggests maybe not.

      --
      use JAPH;
      print JAPH::asString();