Conditional Operator

Conditional Operator

Ternary "?:" is the conditional operator, just as in C. It works much like an if-then-else. If the argument before the ? is true, the argument before the : is returned, otherwise the argument after the : is returned. For example:

    printf "I have %d dog%s.\n", $n,
($n == 1) ? "" : "s";

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;
doc_perl
2016-12-06 03:18:39
Comments
Leave a Comment

Please login to continue.