http://qs321.pair.com?node_id=732286

Dear fellow monks,

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:

sub done { my $self = shift; return not $self->foo and not $self->bar; # gotcha! }

Due to the low precedence of and, the Perl compiler parses this as

(return not $self->foo) and not $self->bar;

which will always return not $self->foo and never evaluate not $self->bar, let alone perform the and. Using the alternative logical operators fixes everything:

sub done { my $self = shift; return !$self->foo && !$self->bar; }

Now, the expression is parsed as return ( (!$self->foo) && (!self->bar) ), which is what I mean. Further surprises of the similar kind include the following line:

my $bool = 1 and 0; # $bool == 1 and $_ == 0; may not be what you expect!

What is your way of avoiding mistakes such as this? Do you avoid using and et al. unless inside parenthesis or in if-else? Some other method of discipline? Peer review? Linting? Agile methods?

--
say "Just Another Perl Hacker";