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:

1
2
    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.

1
2
3
$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):

1
($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:

1
$x % 2 ? $x += 10 : $x += 2

Really means this:

1
(($x % 2) ? ($x += 10) : $x) += 2

Rather than this:

1
($x % 2) ? ($x += 10) : ($x += 2)

That should probably be written more simply as:

1
$x += ($x % 2) ? 10 : 2;
doc_perl
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.