Your skill will accomplish
what the force of many cannot
Operator Precedenceby tomazos (Deacon)
|on Jul 22, 2001 at 15:52 UTC||Need Help??|
A frustrating and dogmatic thing I have heard from the elders that taught me how to write code (not specifically perl) is that:
"You should try not to rely on operator precedence, and use brackets liberally."
They claim this is to help the readability of code to others that may not know the precedence table, and also to avoid making mistakes in your own knowledge of the precedence table.
Perhaps I am just going through a "coding adolescence", where I am questioning everything I have been taught in computer science. I suppose it was finding Perl that has added to it, as Perl does things so differently to the old ways.
But... I think the above statement is untrue. Memorizing the precedence table is not that hard. Even in Perl we are only talking about 50 symbols. That is less than double the number of letters in the alphabet, an ordered list we expect children to learn. Considering most operators are grouped into obvious classes, and much of the precedence we already know from mathematics or other programming languages - it is NOT THAT HARD!
I personally wrote down all the operators on seperate cards one night, and tryed to contruct the operator precedence table on the floor. When I got stuck, I'd look it up in the camel - repeating this until I could construct it - from random to finish - quickly without looking anything up. Only took me a few hours, and because I'm constantly reusing the knowledge it has stuck. I never have to put a bracket in because I am not sure about the precedence again.
I noticed an interesting thing in doing this. Usually you don't need to use brackets at all. The precedence table was designed in a clever way so that most of the time if you are writing your code clearly, you don't need to change precedence at all by using brackets.
If you do have to change the precedence with brackets, most of the time it is because you are not writing your code very clearly - or sometimes it even indicates a logic bug in your thinking.
If you are not sure about the precedence table, than fellow monk, I accuse you of False Laziness! Get the table and take a few hours to memorize it. It will serve you back ten-fold every time you write a line of Perl.
Allow me to offer up some new dogma:
"Memorize the operator precedence table, and do not use unnecessary brackets, it will help you write better code faster."
Update: A set of parenthesis may be necessary to document the meaning of a code to humans - and not to mess with precedence. The point is not to use parenthesis just because you are not sure of the precedence order of operators (something you should know).