Search⌘ K

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.

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:

Perl
$a = 3;
print "\$a = ".$a; #prints $a = 3
$b = ($a = 5); #assigns 5 to $a and then assigns the value of $a to $b
print "\n\$a = ".$a; #prints $a = 5
print "\n\$b = ".$b; #prints $b = 5

Explanation

  1. Line 1 assigns 3 to $a.
  2. Line 3 assigns 5 to $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:

Perl
$a = 1; # basic assignment
print (($a += 2)."\n"); # read as '$a = $a + 2'; $a now is (1 + 2) => 3
print (($a -= 1)."\n"); # $a now is (3 - 1) => 2
print (($a *= 8)."\n"); # $a now is (2 * 8) => 16
print (($a /= 2)."\n"); # $a now is (16 / 2) => 8
print (($a %= 5)."\n"); # $a now is (8 % 5) => 3 (modulus or remainder)
print (($a **= $a)."\n"); # $a now is (3 ^ 3) => 27 (Exponent)

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.