in reply to Efficient Grouping

Just to add my $0.02. I didn't use a hash at all, I used grep.
use strict; my @Group1 = qw( H0 K0 PA PB PC PD PE PF PG PH ); my @Group2 = qw( PX PY PZ P1 P2 P3 P4 P5 P6 P7 ); my @G1_out; my @G2_out; while (my $input = <DATA>) { chomp ($input); my $prefix = substr($input,0,2); # NB: grep is slow in this case. evil. beware. push (@G1_out, $input) if grep($_ eq $prefix, @Group1); push (@G2_out, $input) if grep($_ eq $prefix, @Group2); } print "G1\n"; print "$_\n" foreach @G1_out; print "\nG2\n"; print "$_\n" foreach @G2_out; __DATA__ A1 # invalid K0 # valid G1 B4 # invalid PY # valid G2
Gives:
G1 K0 # valid G1 G2 PY # valid G2
Update: I guess i should've mentioned that i knew it was slower. The bonus I saw is that it doesn't require a hash per group, which i think is a good thing. I guess my priorities lie elsewhere =) My bad.

--
Rock is dead. Long live paper and scissors!

Replies are listed 'Best First'.
Re: Re: Efficient Grouping
by Thelonius (Priest) on Oct 29, 2002 at 18:33 UTC
    Just to clarify, this
    push (@G1_out, $input) if grep($_ eq $prefix, @Group1);
    is a bad idea. It's much slower than the original.

    The hash solutions offered by davorg or tommyw are good except if the possibility exists that the groups are not disjoint. The example given did not overlap, but he did not explicitly say it was impossible.