B.4
Assignment
Scalar variables
are
assigned
scalar values with an
assignment
statement. For instance:
$thousand = 1000;
assigns the integer 1,000, a scalar value, to the scalar variable
$thousand.
The assignment statement looks like an equal sign from elementary
mathematics, but its meaning is different. The assignment statement
is an instruction, not an assertion. It doesn't mean
"$thousand equals 1,000." It means
"store the scalar value 1,000 into the scalar variable
$thousand". However, after the statement,
the value of the scalar variable $thousand is,
indeed, equal to 1000.
You can assign values to several scalar variables by surrounding
variables and values in parentheses and separating them by commas,
thus making lists:
($one, $two, $three) = ( 1, 2, 3);
There are several
assignment
operators besides = that are shorthand for longer
expressions. For instance, $a += $b is equivalent
to $a = $a + $b. Table B-1 is a
complete list (it includes several operators that aren't
covered in this book).
Table B-1. Assignment operator shorthands
Example of operator
|
Equivalent
|
$a += $b
|
$a = $a + $b (addition)
|
$a -= $b
|
$a = $a - $b (subtraction)
|
$a *= $b
|
$a = $a * $b (multiplication)
|
$a /= $b
|
$a = $a / $b (division)
|
$a **= $b
|
$a = $a ** $b (exponentiation)
|
$a %= $b
|
$a = $a % $b (remainder of $a / $b)
|
$a x= $b
|
$a = $a x $b (string $a repeated $b times)
|
$a &= $b
|
$a = $a & $b (bitwise AND)
|
$a |= $b
|
$a = $a | $b (bitwise OR)
|
$a ^= $b
|
$a = $a ^ $b (bitwise XOR)
|
$a >>= $b
|
$a = $a >> $b ($a shift $b bits)
|
$a <<= $b
|
$a = $a >> $b ($a shift $b bits to left)
|
$a &&= $b
|
$a = $a && $b (logical AND)
|
$a ||= $b
|
$a = $a || $b (logical OR)
|
$a .= $b
|
$a = $a . $b (append string $b to $a)
|