Assume variable $a holds 10 and variable $b holds 20, then below are the assignment operators available in Perl and their usage −
Sr.No. | Operator & Description |
---|---|
1 | = Simple assignment operator, Assigns values from right side operands to left side operand Example − $c = $a + $b will assigned value of $a + $b into $c |
2 | += Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand Example − $c += $a is equivalent to $c = $c + $a |
3 | -= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand Example − $c -= $a is equivalent to $c = $c - $a |
4 | *= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand Example − $c *= $a is equivalent to $c = $c * $a |
5 | /= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand Example − $c /= $a is equivalent to $c = $c / $a |
6 | %= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand Example − $c %= $a is equivalent to $c = $c % a |
7 | **= Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand Example − $c **= $a is equivalent to $c = $c ** $a |
Try the following example to understand all the assignment operators available in Perl. Copy and paste the following Perl program in test.pl file and execute this program.
#!/usr/local/bin/perl $a = 10; $b = 20; print "Value of \$a = $a and value of \$b = $b\n"; $c = $a + $b; print "After assignment value of \$c = $c\n"; $c += $a; print "Value of \$c = $c after statement \$c += \$a\n"; $c -= $a; print "Value of \$c = $c after statement \$c -= \$a\n"; $c *= $a; print "Value of \$c = $c after statement \$c *= \$a\n"; $c /= $a; print "Value of \$c = $c after statement \$c /= \$a\n"; $c %= $a; print "Value of \$c = $c after statement \$c %= \$a\n"; $c = 2; $a = 4; print "Value of \$a = $a and value of \$c = $c\n"; $c **= $a; print "Value of \$c = $c after statement \$c **= \$a\n";
When the above code is executed, it produces the following result −
Value of $a = 10 and value of $b = 20 After assignment value of $c = 30 Value of $c = 40 after statement $c += $a Value of $c = 30 after statement $c -= $a Value of $c = 300 after statement $c *= $a Value of $c = 30 after statement $c /= $a Value of $c = 0 after statement $c %= $a Value of $a = 4 and value of $c = 2 Value of $c = 16 after statement $c **= $a