supriyoch_2008 has asked for the wisdom of the Perl Monks concerning the following question:
Hi Perlmonks,
I have a small string my $seq="ATCATCATCATC"; consisting of four 3-letter word i.e. ATC. For all the 3-letter words I am interested in counting the number and the kind of 2-letter at 1st & 2nd positions (AT) of all 3-letter words, similarly for 2nd & 3rd positions (TC) and for 1st & 3rd positions (AC). I have written the following code which gives correct result for 1st & 2nd positions (AT=4) and for 2nd & 3rd positions (TC=4). But I am getting wrong result in counting the number and kind of Letters at 1st & 3rd positions (i.e. AC=0; it should be AC=4).
The code that I have used goes as follows:
#!usr/bin/perl-w my $seq="ATCATCATCATC"; my (%first,%second,%third); my @trilet = $seq =~ /.../g; # Line 4 # Line 5 Perlsyn LOOP foreach my $letters ('AT','TC','AC') { #init $first{ $letters }=0; $second{ $letters }=0; $third{ $letters }=0;# Line 9 } foreach my $tri (@trilet) { # Line 13 perlfunc : substr $first{ substr $tri,0,2 }++; $second{ substr $tri,1,2 }++; # Line 14 $third{ substr $tri,2,2 }++; # Line 15 } foreach my $letters ('AT','TC','AC') { print" Letters At 1st & 2nd Positions:\n"; print " $letters=$first{$letters}; "; # Line 19 } print "\n\n"; foreach my $letters ('AT','TC','AC') { print" Letters At 2nd & 3rd Positions:\n"; print " $letters=$second{$letters}; ";# Line 24 } print "\n\n"; # Line 25 foreach my $letters ('AT','TC','AC') { print" Letters At 1st & 3rd Positions:\n"; print " $letters=$third{$letters}; ";# line 28 } print "\n\n";# Line 30 exit;
I have got the following wrong result for "Letters at 1st & 3rd Positions" in last line of result for AC i.e. AC=0; it should be AC=4
C:\Users\xyz\Desktop>chak.pl Letters At 1st & 2nd Positions: AT=4; Letters At 1st & 2nd Positions: TC=0; Letters At 1st & 2nd Positions: AC=0; Letters At 2nd & 3rd Positions: AT=0; Letters At 2nd & 3rd Positions: TC=4; Letters At 2nd & 3rd Positions: AC=0; Letters At 1st & 3rd Positions: AT=0; Letters At 1st & 3rd Positions: TC=0; Letters At 1st & 3rd Positions: AC=0;(It is wrong; should be AC=4)
I shall be glad if any perlmonk can help me correct the mistake (possibly at Line 15) and further modify the code so that each result comes out after being assigned to a separate scalar variable (like $AT12 for AT at 1st & 2nd positions, similarly $TC12, $AC12 . . . $TC13,$AC13. In the given code, all results come out in a lot.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Why am I getting wrong result in counting the number and kind of 2-letter in 3-letter words in a string?
by johngg (Canon) on May 01, 2012 at 13:57 UTC | |
|
Re: Why am I getting wrong result in counting the number and kind of 2-letter in 3-letter words in a string?
by toolic (Bishop) on May 01, 2012 at 13:39 UTC | |
|
Re: Why am I getting wrong result in counting the number and kind of 2-letter in 3-letter words in a string?
by JavaFan (Canon) on May 01, 2012 at 13:35 UTC |