Assignment Operators
Although it’s not exactly a mathematical operator, we’ve already made
extensive use of the simple assignment operator, = . Try to remember that = means “gets set to” rather than “equals”.
(There is also a mathematical equality operator == that means “equals”, and if you start out
thinking about the difference between them now, you’ll save yourself a
lot of headache later. The ==
operator is like a function that returns a Boolean value, while = is more like a procedure that is evaluated
for the side effect of modifying a variable.)
Like the operators described earlier, assignment operators are binary infix operators, which means they have an operand on either side of the operator. The right operand can be any expression you like, but the left operand must be a valid lvalue (which, when translated to English, means a valid storage location like a variable, or a location in an array). The most common assignment operator is simple assignment. It determines the value of the expression on its right side, and then sets the variable on the left side to that value:
$a = $b; $a = $b + 5; $a = $a * 3;
Notice the last assignment refers to the same variable twice; once for the computation, once for the assignment. There’s nothing wrong with that, but it’s a common enough operation that there’s a shortcut for it (borrowed from C). If you say:
lvalue operator= expression
it is evaluated as if it were:
lvalue = lvalue operator expression
except that the lvalue is not computed twice. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access