Perl Arithmetic Operators Example

Advertisements


Assume variable $a holds 10 and variable $b holds 20 then following are Perl arithmatic operators:

OperatorDescriptionExample
+Addition - Adds values on either side of the operator $a + $b will give 30
-Subtraction - Subtracts right hand operand from left hand operand$a - $b will give -10
*Multiplication - Multiplies values on either side of the operator$a * $b will give 200
/Division - Divides left hand operand by right hand operand$b / $a will give 2
%Modulus - Divides left hand operand by right hand operand and returns remainder$b % $a will give 0
**Exponent - Performs exponential (power) calculation on operators$a**$b will give 10 to the power 20

Example

Try following example to understand all the arithmatic operators available in Perl. Copy and paste 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 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


Advertisements
Advertisements