expression ? if_true_expr : if_false_expr
First, the expression is evaluated to see whether it's true or
false. If it's true, the second expression is used; otherwise,
the third expression is used. Every time, one of the two expressions
on the right is evaluated, and one is ignored. That is, if the first
expression is true, then the second expression is evaluated, and the
third is ignored. If the first expression is false, then the second
is ignored, and the third is evaluated as the value of the whole
thing.
In this example, the result of the subroutine
&is_weekend determines which string expression
will be assigned to the variable:
my $location = &is_weekend($day) ? "home" : "work";
And here, we calculate and print out an average -- or just a
placeholder line of hyphens, if there's no average available:
my $average = $n ? ($total/$n) : "-----";
print "Average: $average\n";
You could always rewrite any use of the ?:
operator as an if structure, often much less
conveniently and less concisely:
my $average;
if ($n) {
$average = $total / $n;
} else {
$average = "-----";
}
print "Average: $average\n";
Here's a trick you might see, used to code up a nice multiway
branch:
my $size =
($width < 10) ? "small" :
($width < 20) ? "medium" :
($width < 50) ? "large" :
"extra-large"; # default
That is really just three nested ?: operators, and
it works quite well, once you get the hang of it.
Of course, you're not obliged to use this operator. Beginners
may wish to avoid it. But you'll see it in others' code,
sooner or later, and we hope that one day you'll find a good
reason to use it in your own programs.