C-Style Logical (Short-Circuit) Operators
Like C, Perl provides the && (logical
and) and || (logical or) operators. Perl also provides a variant of
||, the logical defined or operator, //. These evaluate from left to right (with
&& having slightly higher
precedence than || or //), testing the truth of the statement. These
operators, shown in Table 3-8, 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.
Table 3-8. Logical operators
| Example | Name | Result |
|---|---|---|
$a
&& $b | and | $a if $a is false, $b otherwise |
$a ||
$b | or | $a if $a is true, $b
otherwise |
$a //
$b | Defined or | $a if $a is defined, $b
otherwise |
$a and
$b | Low precedence and | $a if $a is false, $b
otherwise |
$a or
$b | Low precedence or | $a if $a is true, $b
otherwise |
$a xor
$b | Low precedence xor | True if exactly one of $a or $b is true, false otherwise |
Such short circuits not only save time but are also 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 it is skipped. You can read this literally as “Open ...
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