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


in reply to How can I count the number and kinds of letters at 1st, 2nd and 3rd positions of 3-letter words in a string?

Use a hash of hashes rather than individual scalar count variables. You could use unpack to break the string into words and a global regex match and capture for the individual positions.

knoppix@Microknoppix:~$ perl -Mstrict -MData::Dumper -wE ' > my $str = q{ATCGGCGCCTAT}; > my @words = unpack q{(a3)*}, $str; > my %counts; > > foreach my $word ( @words ) > { > my $posn; > $counts{ q{position } . ++ $posn }->{ $1 } ++ > while $word =~ m{(.)}g; > } > > print Data::Dumper->Dumpxs( [ \ %counts ], [ qw{ *counts } ] );' %counts = ( 'position 1' => { 'A' => 1, 'T' => 1, 'G' => 2 }, 'position 3' => { 'T' => 1, 'C' => 3 }, 'position 2' => { 'A' => 1, 'T' => 1, 'C' => 1, 'G' => 1 } ); knoppix@Microknoppix:~$

I hope this is helpful.

Cheers,

JohnGG

  • Comment on Re: How can I count the number and kinds of letters at 1st, 2nd and 3rd positions of 3-letter words in a string?
  • Download Code