use Modern::Perl; use Sort::Naturally; my ( $str, %i, %positions ) = 'BATCATDATEFEAT'; $str =~ s/(A|T)/$positions{$1 . '=' . ++$i{$1}}=pos($str)+1/ige; open my $fh, '>', 'Results.txt' or die $!; say $fh "$_ ends at $positions{$_}" for nsort keys %positions; close $fh;