Perl Operators Precedence Example


Advertisements


The following table lists all operators from highest precedence to lowest.

left	terms and list operators (leftward)
left	->
nonassoc	++ --
right	**
right	! ~ \ and unary + and -
left	=~ !~
left	* / % x
left	+ - .
left	<< >>
nonassoc	named unary operators
nonassoc	< > <= >= lt gt le ge
nonassoc	== != <=> eq ne cmp ~~
left	&
left	| ^
left	&&
left	|| //
nonassoc	..  ...
right	?:
right	= += -= *= etc.
left	, =>
nonassoc	list operators (rightward)
right	not
left	and
left	or xor

Example

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

#!/usr/local/bin/perl

$a = 20;
$b = 10;
$c = 15;
$d = 5;
$e;

print "Value of \$a  = $a, \$b = $b, \$c = $c and \$d = $d\n";
 
$e = ($a + $b) * $c / $d;
print "Value of (\$a + \$b) * \$c / \$d is  = $e\n";

$e = (($a + $b) * $c )/ $d;
print "Value of ((\$a + \$b) * \$c) / \$d is  = $e\n";

$e = ($a + $b) * ($c / $d);
print "Value of (\$a + \$b) * (\$c / \$d ) is  = $e\n";

$e = $a + ($b * $c ) / $d;
print "Value of \$a + (\$b * \$c )/ \$d is  = $e\n";

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

Value of $a = 20, $b = 10, $c = 15 and $d = 5
Value of ($a + $b) * $c / $d is = 90
Value of (($a + $b) * $c) / $d is = 90
Value of ($a + $b) * ($c / $d ) is = 90
Value of $a + ($b * $c )/ $d is = 50

perl_operators.htm

Advertisements