Node:Numerical Operators, Next:, Previous:Operators, Up:Operators



Numerical Operators

The basic numerical operators in Perl are like others that you might see in other high level languages. In fact, Perl's numeric operators were designed to mimic those in the C programming language.

First, consider this example:

     use strict;
     my $x = 5 * 2 + 3;     # $x is 13
     my $y = 2 * $x / 4;    # $y is 6.5
     my $z = (2 ** 6) ** 2; # $z is 4096
     my $a = ($z - 96) * 2; # $a is 8000
     my $b = $x % 5;        # 3, 13 modulo 5
     

As you can see from this code, the operators work similar to rules of algebra. When using the operators there are two rules that you have to keep in mind--the rules of precedence and the rules of associativity.

Precedence involves which operators will get evaluated first when the expression is ambiguous. For example, consider the first line in our example, which includes the expression, 5 * 2 + 3. Since the multiplication operator (*) has precedence over the addition operator (+), the multiplication operation occurs first. Thus, the expression evaluates to 10 + 3 temporarily, and finally evaluates to 13. In other words, precedence dictates which operation occurs first.

What happens when two operations have the same precedence? That is when associativity comes into play. Associativity is either left or right 1. For example, in the expression 2 * $x / 4 we have two operators with equal precedence, * and /. Perl needs to make a choice about the order in which they get carried out. To do this, it uses the associativity. Since multiplication and division are left associative, it works the expression from left to right, first evaluating to 26 / 4 (since $x was 13), and then finally evaluating to 6.5.

Briefly, for the sake of example, we will take a look at an operator that is left associative, so we can contrast the difference with right associativity. Notice when we used the exponentiation (**) operator in the example above, we had to write (2 ** 6) ** 2, and not 2 ** 6 ** 2.

What does 2 ** 6 ** 2 evaluate to? Since ** (exponentiation) is right associative, first the 6 ** 2 gets evaluated, yielding the expression 2 ** 36, which yields 68719476736, which is definitely not 4096!

Here is a table of the operators we have talked about so far. They are listed in order of precedence. Each line in the table is one order of precedence. Naturally, operators on the same line have the same precedence. The higher an operator is in the table, the higher its precedence.

Operator Associativity Description
** right exponentiation
*, /, % left multiplication, division, modulus
+, - left addition, subtraction


Footnotes

  1. Some operators are not associative at all (see Summary of Scalar Operators).