Logical Operators

Perl provides the && (logical AND) and || (logical OR) operators. They evaluate from left to right testing the truth of the statement.

Example

Name

Result

$a && $b

And

$a if $a is false, $b otherwise

$a || $b

Or

$a if $a is true, $b otherwise

For example, an oft-appearing idiom in Perl programs is:

open(FILE, "somefile") || die "Cannot 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 is skipped.

Perl also provides lower-precedence and and or operators that are more readable.

Get Perl in a Nutshell, 2nd 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.