http://www.perlmonks.org?node_id=986061


in reply to How can I get the results in a text file from counting in a string?

kennethk has provided great targeted script advice. Here's another coding option:

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;

Output to file:

Position of A ends at 2 Position of T ends at 3 Position of A ends at 5 Position of T ends at 6 Position of A ends at 8 Position of T ends at 9 Position of A ends at 13 Position of T ends at 14

This option uses the e modifier in the substitution to execute the embedded code, which holds position/letter (key/value) pairs in a hash. The printing part numerically sorts the keys, sending the output to Results.txt.

Hope this helps!

Update: by modifying the script a little, it can generate your output:

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;

Output to file:

A=1 ends at 2 A=2 ends at 5 A=3 ends at 8 A=4 ends at 13 T=1 ends at 3 T=2 ends at 6 T=3 ends at 9 T=4 ends at 14

Here, Sort::Naturally is used to sort the keys which have mixed content, e.g., A=1.