< BACKCONTINUE >

9.3 Perl Operations

We've made it pretty far in this introductory programming book without talking about basic arithmetic operations, because you haven't really needed much more than addition to increment counters.

However, an important part of any programming language, Perl included, is the ability to do mathematical calculations. Look at Appendix B, which shows the basic operations available in Perl.

9.3.1 Precedence of Operations and Parentheses

Operations have rules of precedence. These enable the language to decide which operations should be done first when there are a few of them in a row. The order of operations can change the result, as the following example demonstrates.

Say you have the code 8 + 4 / 2. If you did the division first, you'd get 8 + 2, or 10.However, if you did the addition first, you'd get 12 / 2, or 6.

Now programming languages assign precedences to operations. If you know these, you can write expressions such as 8 + 4 / 2, and you'd know what to expect. But this is a slippery slope.

For one thing, what if you get it wrong? Or, what if someone else has to read the code who doesn't have the memorization powers you do? Or, what if you memorize it for one language and Perl does it differently? (Different languages do indeed have different precedence rules.)

There is a solution, and it's called using parentheses. For Example 9-3, if you simply add parentheses: (8 + ( 4 / 2 )), it's clear to you, other readers, and the Perl program, that you want to do the division first. Note that "inner" parentheses, contained within another pair of parentheses, are evaluated first.

Remember to use parentheses in complicated expressions to specify the order of operations. Among other things, it will save you some long debugging sessions!

< BACKCONTINUE >

Index terms contained in this section

() (parentheses)
      order of operations, specifying with
arithmetic operators
      order of evaluation
operators
      arithmetic
Perl
      arithmetic operations
precedence
      arithmetic operations

© 2002, O'Reilly & Associates, Inc.