http://qs1969.pair.com?node_id=98813


in reply to Operator Precedence

In Perl there are many ways to do it. In production code the reality is that someone with less experience/knowledge/patience than you may one day have to maintain your code. Sure you can do it in one line. Sure you don't need brackets, or pod or comments or long var names..... to make your code run. We add all these things to make the code easier to debug, easier to understand, and easier to maintain. With parenths precedence is a gimmee, without it may not be. Perhaps one of the commenest problems I see on PM is why doesn't this work:

open FILE, "<$file" || die "Oops $!\n";

Sure all you need to do is add brackets or change the || to 'or' but this is not obvious. This aside I find code like this:

print ("Hello World!\n"); close (FILE);

anoying as there is no precedence issue being addressed by the brackets - probably just a C hangover. There are however some problematic examples like:

/foo/ ? $a += 1 : $a -= 1; # parses as (/foo/ ? $a += 1 : $a) -= 1; # but $a += /foo/ ? 1 : -1; # will work as expected.

Shorter is not always better. Never expect anyone to understand what you are trying to do as well as you do. Adding parenths takes a fraction of a second if you touch type. Sure don't go overboard but save your precedence expertise for GOLF. Personally I vividly recall precedence issues causing *interesting* bugs. I felt sure that I knew the precedence until I stepped through the code and realised Perl and I did not share the same views! This said brackets are not always good, consider these examples - the last fails.

$_ = 'foo'; /foo/ ? print "Found foo\n" : print "No foo here\n"; (/foo/) ? print "Found foo\n" : print "No foo here\n"; print /foo/ ? "Found foo\n" : "No foo here\n"; print (/foo/) ? "Found foo\n" : "No foo here\n";

cheers

tachyon

s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print