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