perlmeditation
vrk
<p>
Dear fellow monks,
</p>
<p>
recently, perhaps due to some slight change in my programming, I have frequently found myself debugging mysterious bugs where, after three or four careful readings of the source code, there are seemingly none. Most of these have boiled down to misunderstanding precedence rules. Example:
</p>
<code>
sub done {
my $self = shift;
return not $self->foo and not $self->bar; # gotcha!
}
</code>
<p>
Due to the low precedence of <code>and</code>, the Perl compiler parses this as
</p>
<code>
(return not $self->foo) and not $self->bar;
</code>
<p>
which will always return <code>not $self->foo</code> and never evaluate <code>not $self->bar</code>, let alone perform the <code>and</code>. Using the alternative logical operators fixes everything:
</p>
<code>
sub done {
my $self = shift;
return !$self->foo && !$self->bar;
}
</code>
<p>
Now, the expression is parsed as <code>return ( (!$self->foo) && (!self->bar) )</code>, which is what I mean. Further surprises of the similar kind include the following line:
</p>
<code>
my $bool = 1 and 0;
# $bool == 1 and $_ == 0; may not be what you expect!
</code>
<p>
What is your way of avoiding mistakes such as this? Do you avoid using <code>and</code> et al. unless inside parenthesis or in if-else? Some other method of discipline? Peer review? Linting? Agile methods?
</p>
<div class="pmsig">
<div class="pmsig-399589">
<p>
-- <br>
say "Just Another [href://http://prometheus.frii.com/~gnat/yapc/2000-stages/slide36.html|Perl Hacker]";
</p>
</div>
</div>