My Favorite Warnings: precedence

Perl possesses a rich and expressive set of operators. So rich, in fact, that other adjectives can come to mind, such as prolix, or even Byzantine.

Requests for help navigating Perl's operator space appear repeatedly on outlets such as PerlMonks. These seem to me to involve two sorts of confusion: precedence (discussed here) and functionality (string versus numeric -- maybe another blog post).

The precedence warnings category has some help here, though as of Perl 5.34 there are only two diagnostics under it:

Precedence problem: open %s should be open(%s)

This involves the "open a file or die" idiom. It seems that in very early versions of Perl (4 and earlier?) there was a special case in the compiler allowing the use of the double-pipe logical or operator ('||') in this idiom. This disappeared before I first started using Perl, in favor of the low-precedence 'or' operator. But because the internet never forgets anything people learning Perl from Google try to use it. Unfortunately they do not learn use warnings; from such sources, hence the questions.

Possible precedence problem on bitwise %s operator

This involves the fact that the bitwise logical operators have lower precedence than the comparison operators, so that $x & $y == $z compiles unexpectedly (to some, including me) to $x & ( $y == $z ).

My impression is that most of the precedence queries on places like PerlMonks come from the fact that Perl has two sets of Boolean operators, differing only in precedence. An inexperienced Perl programmer trying to write clear code might choose 'and' over '&&' because it is less cryptic, and then fall over the fact that its precedence is lower than the assignment operator.

It is hard to see how the Perl compiler could deliver useful warnings in more than a fraction of these cases, at least not without a Vulcan Mind Meld interface to determine what the programmer actually meant. There is a Perl::Critic policy that tries to deal with this (::ValuesAndExpressions::ProhibitMixedBooleanOperators), but unless the neophyte has a Perl support system perlcritic is unlikely to be available. And anyway this specific policy looks like training wheels to me, Perl Best Practices to the contrary notwithstanding.

Previous entries in this series:

  1. A Belated Introduction
  2. once
  3. redundant and missing
  4. exiting
  5. uninitialized
  6. redefine
  7. Ex-Warnings
  8. deprecated
  9. experimental
  10. shadow
  11. syntax
  12. ambiguous
  13. closure
  14. qw

Leave a comment

About Tom Wyant

user-pic I blog about Perl.