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