Perl 运算符优先级示例


下表列出了从最高优先级到最低优先级的所有运算符。

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

例子

尝试以下示例来了解 Perl 中所有 Perl 运算符的优先级。将以下 Perl 程序复制并粘贴到 test.pl 文件中并执行该程序。

#!/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";

执行上述代码时,会产生以下结果 -

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