Limbic~Region has asked for the wisdom of the Perl Monks concerning the following question:
All,
I have looked through the Monastery, but haven't found anything in Tutorials covering precedence. Of course one should read perlop (Perl operators and precedence), but sometimes we need something a little more basic. For instance, I often use the following code:
I have looked through the Monastery, but haven't found anything in Tutorials covering precedence. Of course one should read perlop (Perl operators and precedence), but sometimes we need something a little more basic. For instance, I often use the following code:
On the other hand, if I am using the modulus operator (%) to see if a number is divisible by another, I use:sub new { my $class = shift; croak "incorrect number of arguments" if @_ % 2; ... }
Why didn't I use if ! $foo % $bar;? The answer is precedence. In order to get that to work the way I wanted, I would need to use if not $foo % $bar; or if ! ($foo % $bar);. For people who can't commit the precedence chart to memory, they end up putting parens everywhere. While I find the following Larry quote humorous - there is too much of a good thing:print "$foo is divisible by $bar" if $foo % $bar == 0;
When in doubt, parenthesize. At the very least it will let some poor schmuck bounce on the % key in vi. - From perlstyle
Unfortunately, I haven't assimilated the knowledge I think is necessary to write such a tutorial. I was hoping others could provide classic pitfalls like the one I described, rules of thumb, how to remember the chart, etc. Actually, I am hoping someone just volunteers to write the tutorial and I can reap the benefits but I am willing to consolidate the responses and write the tutorial myself.Cheers - L~R
|
---|
Back to
Seekers of Perl Wisdom