Perl Arithmetic Operators Example


Advertisements


Assume variable $a holds 10 and variable $b holds 20, then following are the Perl arithmatic operators −

Sr.No. Operator & Description
1

+ ( Addition )

Adds values on either side of the operator

Example − $a + $b will give 30

2

- (Subtraction)

Subtracts right hand operand from left hand operand

Example −$a - $b will give -10

3

* (Multiplication)

Multiplies values on either side of the operator

Example −$a * $b will give 200

4

/ (Division)

Divides left hand operand by right hand operand

Example −$b / $a will give 2

5

% (Modulus)

Divides left hand operand by right hand operand and returns remainder

Example −$b % $a will give 0

6

** (Exponent)

Performs exponential (power) calculation on operators

Example −$a**$b will give 10 to the power 20

Example

Try the following example to understand all the arithmatic operators available in Perl. Copy and paste the following Perl program in test.pl file and execute this program.

#!/usr/local/bin/perl
 
$a = 21;
$b = 10;

print "Value of \$a = $a and value of \$b = $b\n";

$c = $a + $b;
print 'Value of $a + $b = ' . $c . "\n";

$c = $a - $b;
print 'Value of $a - $b = ' . $c . "\n";

$c = $a * $b;
print 'Value of $a * $b = ' . $c . "\n";

$c = $a / $b;
print 'Value of $a / $b = ' . $c . "\n";

$c = $a % $b;
print 'Value of $a % $b = ' . $c. "\n";

$a = 2;
$b = 4;
$c = $a ** $b;
print 'Value of $a ** $b = ' . $c . "\n";

When the above code is executed, it produces the following result −

Value of $a = 21 and value of $b = 10
Value of $a + $b = 31
Value of $a - $b = 11
Value of $a * $b = 210
Value of $a / $b = 2.1
Value of $a % $b = 1
Value of $a ** $b = 16

perl_operators.htm

Advertisements