06 Jul 2009

How to use Perl’s ternary operator

Perl; The Ternary Operator

The ternary is actually a sequence of operators. The operator is used like this:

CONDITION-PART ? TRUE-PART : FALSE-PART

which is shorthand for the following statement:

if (CONDITION-PART) {
    TRUE-PART
} else {
    FALSE-PART
}

Example: If $firstVar is zero, then assign $secondVar a value of zero. Otherwise, assign $secondVar the value in the first element in the array @array.

$secondVar = ($firstVar == 0) ? 0 : $array[0];

via Perl 5 By Example.