sub comNucCount {
my($string1, $string2) = @_;
$string1 = lc $string1;
$string2 = lc $string2;
# we assume that the strings have the same length
my($length) = length($string1);
my($position);
my($a,$c,$g,$t) = "0";
for ($position=0; $position < $length ; ++$position) {
if(substr($string1,$position,1) eq substr($string2,$position,1)) {
if(substr($string1,$position,1) eq 'a'){$a++}
if(substr($string1,$position,1) eq 'c'){$c++}
if(substr($string1,$position,1) eq 'g'){$g++}
if(substr($string1,$position,1) eq 't'){$t++}
}
}
return "A=$a, C=$c, G=$g, T=$t";
}
Without really checking your code in detail, it looks like you want this:
my($a,$c,$g,$t) = (0, 0, 0, 0); # or my($a,$c,$g,$t) = (0) x 4;
Your version:
my($a,$c,$g,$t) = "0";That initializes $a to "0" and doesn't assign any value to the other variables.
Cheers,
Ovid
New address of my CGI Course.
The error occur because you're are only initializting $a. Try:
my ($a,$c,$g,$t) = (0, 0, 0, 0);
or
my $a = 0; my $c = 0; my $g = 0; my $t = 0;
Notice the lack of quotes around a numerical zero.
Another way to do it - avoid all that fiddly substr stuff:
use strict;
use warnings;
print comNucCount('acgtacgtacgtacgt', 'aaaaccccggggtttt'), "\n";
sub comNucCount {
my @str1 = split '', lc shift;
my @str2 = split '', lc shift;
my %counts = (a => 0, c => 0, g => 0, t => 0);
for (@str1) {
last if ! @str2; # Length mismatch - done
$counts{$_}++ if $_ eq shift @str2;
}
return "A=$counts{'a'}, C=$counts{'c'}, G=$counts{'g'}, T=$counts{'t'}";
}
Prints:
A=1, C=1, G=1, T=1
perlmonks.org content © perlmonks.org and dunno260, GrandFather, ikegami, Ovid
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03