Perl Operators   «Prev 

Perl Ternary Operators

In computer programming, the following notation ?: is a ternary operator that is part of the syntax for basic conditional expressions. It is commonly referred to as the conditional operator or ternary if.
Operator Description
? : if then else

The ternary operator uses three expressions to do its work:
$x = $a ? $b : $c

This operator evaluates from left to right:
  1. $a is evaluated.
  2. If $a is nonzero, $b is evaluated and returned.
  3. Otherwise, $c is evaluated and returned.

So, given this:
$a = 1; $b = 2; $c = 3;
$x = $a ? $b : $c;

The value of $b (2) is assigned to $x. If $a were zero or undefined, the value of $c would be assigned to $x.
Note that if $a evaluates to true (non-zero), then $b will be evaluated, but $c will not. If $a evaluates to false (zero), then $c will be evaluated but $b will not.
Thus you should not write code using the ternary operator that depends on both $b and $c being evaluated.