Assignment Operators
Understand how Perl assignment operators work by exploring the use of the basic = operator for value assignment and combined assignment shortcuts. Learn to differentiate between = for assigning and == for comparison to write accurate Perl code.
We'll cover the following...
Basic assignment
Perl allows you to do the basic arithmetic assignment by using the = operator.
The above statement results in $a having the value “hello”. The result of an assignment expression is the value being assigned. Note that a single equal sign = is NOT for
comparison!
Example
Run the following code to see what happens:
Explanation
- Line 1 assigns
3to$a. - Line 3 assigns
5to$a, and later assigns the result of the expression in parentheses ($a=5) to$b.
Thus, both $a and $b now have the value 5.
Combined assignment
The combined assignment operators are a shortcut for an operation on some variable and subsequently assigning this new value to that variable.
Example
Run the code below to see how combined assignment works:
Difference between = and == operator
We use = to assign value to the variable:
$variable = 10;
while == is used to compare the value that variable contains:
$variable = 10;
if(variable == 10) # returns true.