# my %freq; #<---- uncomment this somewhere before your loop # through the file to instantiate the hash if ($line=~m/$sequence(.{11})(.{11})$sequence/){ $freq{$1}++; $freq{$2}++; } } # after all lines are read in.... # sort through the sequences, highest frequency to lowest for my $seq (sort { $freq{$b} <=> $freq{$a} } keys %freq){ print "$seq $freq{$seq}\n"; }