my @Group1 = qw( H0 K0 PA PB PC PD PE PF PG PH ); #etc my @Group2 = qw( PX PY PZ P1 P2 P3 P4 P5 P6 P7 ); #etc # etc, 6 lists defined, with 100-200 prefixes each foreach my $code (@Group1) { $G1_Hash{$code} = 1; } foreach my $code (@Group2) { $G2_Hash{$code} = 1; } while (my $input = ) { chomp ($input); my $prefix = substr($input,0,2); push (@G1_out, $input) if $G1_Hash{$prefix}; push (@G2_out, $input) if $G2_Hash{$prefix}; }