Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

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";

In reply to Burned by precedence rules by vrk

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others imbibing at the Monastery: (4)
    As of 2018-01-22 20:58 GMT
    Find Nodes?
      Voting Booth?
      How did you see in the new year?

      Results (237 votes). Check out past polls.