Hi, Sean.
Quoting Sean Quinlan <[EMAIL PROTECTED]>:
> while($codon = &$read_code) {
> .....
> my $out = _stop(\$seq1,$pos,$minlen,$id) if $seq1 =~ /\.$/;
> .....
> } # while reading codons from genome
> .....
> The above code causes the same fragment to be output multiple times.
The problem is that the "if" statement modifier applies not just to the
assignment of $out, but also to the localization expected by "my". If $seq1
does not match the regular expression, the variable $out refers to the old
value from the previous run of the "while" loop.
> There doesn't seem to
> be any obvious pattern to how many times the output would be repeated,
> but I didn't bother to investigate that deeply. Changing the "my $out =
> _stop" line in the while loop above to:
> my $out = '';
> $out .= _stop(\$seq1,$pos,$minlen,$id) if $seq1 =~ /\.$/;
> Seems to have completely solved the problem. Is this some sort of
> mistake on my part, some subtle/odd behavior that would cause this to be
> expected in this usage (and if so please explain)....
In this case, the "my" statement is not conditionalized, as it was with the "if"
statement modifier in the first code segment.
Try this example for clarity:
#!/usr/bin/perl
use strict;
use warnings;
my @a;
print "First variation:\n";
@a = (1..10);
while (my $i = shift @a) {
my $number = "Greater than 5: " if $i > 5;
$number .= $i;
print "$number\n";
}
print "Second variation:\n";
@a = (1..10);
while (my $i = shift @a) {
my $number = "";
$number = "Greater than 5: " if $i > 5;
$number .= $i;
print "$number\n";
}
Here is the output:
First variation:
1
12
123
1234
12345
Greater than 5: 6
Greater than 5: 7
Greater than 5: 8
Greater than 5: 9
Greater than 5: 10
Second variation:
1
2
3
4
5
Greater than 5: 6
Greater than 5: 7
Greater than 5: 8
Greater than 5: 9
Greater than 5: 10
Notice that the conditional "my" in the first variation causes the value of
$number to accumulate the loop iterator, rather than just being set to a single
digit as in the second. "use strict" and "use warnings" fail to alert the
programmer to this problem, because the variable $number does get properly
declared with "my" at least some of the time. I am not sure if that failure to
alert counts as a bug or not. It is a tricky little catch.
+ Richard
_______________________________________________
Boston-pm mailing list
[email protected]
http://mail.pm.org/mailman/listinfo/boston-pm