
| Contents |
|||||||||||||||||||||||||||||||||||||||||
| [an error occurred while processing this directive] |
2.4.1 Numerical OperatorsThe 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,
What happens when two operations have the same precedence? That is when
associativity comes into play. Associativity is either left or right
(7). For example, in the expression
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 (
What does 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.
|