- 论坛徽章:
- 46
|
操作符优先级的问题 = 比 ?: 要低。说实话在 ?: 中用稍微复杂点的表达式我都分不清优先级的,所以我不这么用。摘抄 perlop
Conditional Operator
Ternary "?:" is the conditional operator, just as in C.
Scalar or list context propagates downward into the 2nd or 3rd argument, whichever is selected.
$x = $ok ? $y : $z; # get a scalar
@x = $ok ? @y : @z; # get an array
$x = $ok ? @y : @z; # oops, that's just a count!
The operator may be assigned to if both the 2nd and 3rd arguments are legal lvalues (meaning that you can assign to them):
($x_or_y ? $x : $y) = $z;
Because this operator produces an assignable result, using assignments without parentheses will get you in trouble. For example, this:
$x % 2 ? $x += 10 : $x += 2
Really means this:
(($x % 2) ? ($x += 10) : $x) += 2
Rather than this:
($x % 2) ? ($x += 10) : ($x += 2)
That should probably be written more simply as:
$x += ($x % 2) ? 10 : 2; |
|