# Perl Assignment Operators Example

Advertisements

Assume variable $a holds 10 and variable $b holds 20, then below are assignment operators available in Perl and their usage −

Operator | Description | Example |
---|---|---|

= | Simple assignment operator, Assigns values from right side operands to left side operand | $c = $a + $b will assigned value of $a + $b into $c |

+= | Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand | $c += $a is equivalent to $c = $c + $a |

-= | Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand | $c -= $a is equivalent to $c = $c - $a |

*= | Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand | $c *= $a is equivalent to $c = $c * $a |

/= | Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand | $c /= $a is equivalent to $c = $c / $a |

%= | Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand | $c %= $a is equivalent to $c = $c % a |

**= | Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand | $c **= $a is equivalent to $c = $c ** $a |

## Example

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

perl_operators.htm

Advertisements