C-Style Logical (Short-Circuit) Operators
Like C, Perl provides the &&
(logical AND) and ||
(logical OR) operators. They
evaluate from left to right (with &&
having
slightly higher precedence than ||
) testing the
truth of the statement. These operators are known as short-circuit
operators because they determine the truth of the statement by
evaluating the fewest number of operands possible. For example, if the
left operand of an &&
operator is false,
the right operand is never evaluated because the result of the
operator is false regardless of the value of the right operand.
Example | Name | Result |
---|---|---|
$a && $b | And | $a if $a is
false, $b otherwise |
$a || $b | Or |
|
Such short circuits not only save time, but are frequently used to control the flow of evaluation. For example, an oft-appearing idiom in Perl programs is:
open(FILE, "somefile") || die "Can't open somefile: $!\n";
In this case, Perl first evaluates the open
function. If the value is true (because somefile
was successfully opened), the execution of the die
function is unnecessary, and so is skipped. You can read this
literally as "Open some file or die!"
The &&
and ||
operators differ from C's in that, rather than returning 0 or 1, they
return the last value evaluated. In the case of ||
,
this has the delightful result that you can select the first of a
series of scalar values that happens to be true. Thus, a reasonably
portable way to find out the user's home directory might be:
$home = $ENV{HOME} || $ENV{LOGDIR} ...
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.