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 function 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.)
my $a = $ok ? $b : $c; # get a scalar my @a = $ok ? @b : @c; # get an array my $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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access