A.4 Assignment

Scalar variables are assigned scalar values with an assignment operator (the equals sign) in an assignment statement:

$thousand = 1000;

assigns the integer 1000, 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 1000." It means "store the scalar value 1000 into the scalar variable $thousand". However, after the statement, the value of the scalar variable $thousand is, indeed, equal to 1000.

References are usually saved in scalar variables. For example:

$pi = \3.14159265;

If you try to print $pi after this assignment, you get an indication that it's a reference to a scalar value at a memory location represented in hexadecimal digits. To print the value of a variable that's a reference to a scalar, precede its name with an additional dollar sign:

print $pi,"\n";
print $$pi, "\n";

This gives the output:

SCALAR(0x811d1bc)
3.14159265

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 A-1 is a complete list.

Table A-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)