3.14. 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 | $a if $a is true, $b otherwise |
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}
|| (getpwuid($<))[7]
|| die "You're homeless!\n";
On the other hand, since the left argument is always evaluated in scalar
context, you can't use || for selecting between two aggregates
for assignment:
@a = @b || @c; # This doesn't do the right thing
@a = scalar(@b) || @c;# because it really means this.
@a = @b ? @b : @c; # This works fine, though.
Perl also provides lower precedence and and
or operators that some people find more readable
and don't force you to use parentheses on list operators. They also
short-circuit. See Table 3-1 for a
complete list.