J2EEOnline J2EE

Perl Operators   «Prev  Next»
Lesson 15

Perl operators Conclusion

This module discussed Perl's operators and how to use them to solve common programming problems. In the process, you have learned about operator precedence and how the relative precedence of the operators affects the way your expressions are evaluated.
By now you should be able to write simple programs to handle some of your programming tasks.
In the next module, you will learn the power of regular expressions, and your ability to write effective system administration and general text manipulation programs will increase significantly.

Perl Operator - Quiz

Before you move onto the next module, make sure to click the Quiz link below to take a multiple-choice quiz that has questions addressing all of the lessons we have worked through in this module.
Perl Operator - Quiz

The Unary Arithmetic Operators

In common with C, Perl has two short hand unary operators that can prove useful. The unary arithmetic operators act on a single operand. They are used to change the sign of a value, to increment a value, or to decrement a value. Incrementing a value means to add one to its value. Decrementing a value means to subtract one from its value. In many statements we frequently write something like:

$a = $a + 1;

we can write this more compactly as: $a += 1; .
This works for any operator so this is equivalent:
$a = $a * $b;
$a *= $b;

You can also automatically increment and decrement variables in Perl with the ++ and -- operators. For example all three expressions below achieve the same result:
$a = $a + 1;
$a += 1;

The ++ and -- operators can be used in prefix and postfix mode in expressions. There is a difference in their use. In Prefix the operator comes before the variable and this indicates that the value of the operation be used in the expression: I.e.
$a = 3;
$b = ++$a;

results in a being incremented to 4 before this new value is assigned to b. That is to say BOTH a and b have the value 4 after these statements have been executed. In postfix the operator comes after the variable and this indicates that the value of the variable before the operation be used in the expression and then the variable is incremented or decremented.
$a = 3;
$b = $a++;