my %keys = ( a=>1, e=>2, i=>3, o=>4, u=>5, ); my @records = (); push @records, '1|2|3|d|4'; push @records, '1|2|3|a|4'; push @records, '1|2|3|d|4'; push @records, '1|2|3|o|4'; my @final = (); my @result = (); my $re = ''; map {my @flds=split /\|/; push @{$final[$keys{$flds[3]}||0]},$_} @records; # note that entry 0 is where the unmatched elements wind up... print map{ "@{ $final[$_] }\n" } grep defined $final[$_],1..$#final; #### foreach(@records) { my @flds=split /\|/; push @{$final[$keys{$flds[3]}||0]},$_; }