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 = ) { 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 #### G1 K0 # valid G1 G2 PY # valid G2