Assignment Operators

Yesterday, we discussed the basic assignment operator, =, which assigns a value to a variable. One common use of assignment is an operation to change the value of a variable based on the current value of that variable, such as:

$inc = $inc + 100;

This does exactly what you'd expect; it gets the value of $inc, adds 100 to it, and then stores the result back into $inc. This sort of operation is so common that there is a shorthand assignment operator to do just that. The variable reference goes on the left side, and the amount to change it on the right, like this:

$inc += 100;

Perl supports shorthand assignments for each of the arithmetic operators, for string operators I haven't described yet, and even for && and ||. Table 3.1 shows a few of the shorthand assignment operators. Basically, just about any operator that has two operands has a shorthand assignment version, where the general rule is that

						variable operator= expression
					

is equivalent to

						variable = variable operator expression
					

There's only one difference between the two: in the longhand version, the variable reference is evaluated twice, whereas in the shorthand it's only evaluated once. Most of the time, this won't affect the outcome of the expression, just keep it in mind if you start getting results you don't expect.

Table 3.1. Some Common Assignment Operators
Operator Example Longhand equivalent
+= $x += 10 $x = $x + 10
-= $x -= 10 $x = $x - 10
*= $x *= 10 $x = $x * 10
/= $x /= 10 $x = $x / 10
%= $x %= 10 $x = $x % 10
**= $x **= 10 $x = $x**10

Note that the pattern matching operator, =~, is not an assignment operator and does not belong in this group. Despite the presence of the equals sign (=) in the operator, pattern matching and variable assignment are entirely different things.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset