Conditional Operator

As in C, ?: is the only trinary operator. It's often called the conditional operator because it works much like an if-then-else, except that, since it's an expression and not a statement, it can be safely embedded within other expressions and functions calls. As a trinary operator, its two parts separate three expressions:

COND ? THEN : ELSE

If the condition COND is true, only the THEN expression is evaluated, and the value of that expression becomes the value of the entire expression. Otherwise, only the ELSE expression is evaluated, and its value becomes the value of the entire expression.

Scalar or list context propagates downward into the second or third argument, whichever is selected. (The first argument is always in scalar context, since it's a conditional.)

$a = $ok ? $b : $c;  # get a scalar
@a = $ok ? @b : @c;  # get an array
$a = $ok ? @b : @c;  # get a count of an array's elements

You'll often see the conditional operator embedded in lists of values to format with printf, since nobody wants to replicate the whole statement just to switch between two related values.

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

Conveniently, the precedence of ?: is higher than a comma but lower than most operators you'd use inside (such as == in this example), so you don't usually have to parenthesize anything. But you can add parentheses for clarity if you like. For conditional operators nested within the THEN parts of other conditional operators, we suggest ...

Get Programming Perl, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.