In expressions where more than one operator is in use, some parts of the expression will be evaluated before other parts.
The rules that dictate this are based on a concept called
operator precedence.
The operators which have higher precedence are evaluated before the operators with lower precedence.
For example, consider this expression:
$x = 5 * 3 + 4;
Take a look at the following code:
$x = 5 * 3 + 4;
Since the precedence of the multiplication operator (
*
) is higher than that of the addition operator ( + ),
the multiplication is evaluated first, so the result is (5 * 3) + 4, or 19.
If this is not what you meant, you can always use parenthesis, like this:
$x = 5 * (3 + 4);
Perl provides the typical ordinary addition, subtraction, multiplication, and division
operators, and so on. For example:
2 + 3 # 2 plus 3, or 5
5.1 - 2.4 # 5.1 minus 2.4, or 2.7
3 * 12 # 3 times 12 = 36
14 / 2 # 14 divided by 2, or 7
#
10.2 / 0.3 # 10.2 divided by 0.3, or 34
10 / 3 # always floating-point divide, so 3.3333333...
Perl also supports a modulus operator (%). The value of the expression 10 % 3 is the remainder when 10 is divided by 3, which is 1. Both values are first reduced to their integer values, so 10.5 % 3.2 is computed as 10 % 3.* Additionally, Perl provides the FORTRAN-like exponentiation operator, which many have yearned for in Pascal and C. The operator is represented by the double asterisk, such as 2**3, which is two to the third power, or eight.
In addition, there are other numeric operators.
Will the
value of$x
be 19 (15 + 4) or
35 (5 * 7)?
Use this
list of operators, in order of precedence, for reference throughout this module.
The rest of this module is not in the order of precedence. The order was chosen to put related operators together, and to give you the operators first that will help you understand the later ones.
In the next lesson you will learn about the basic math operators.