Skip to Main Content
Programming Perl, 3rd Edition
book

Programming Perl, 3rd Edition

by Larry Wall, Tom Christiansen, Jon Orwant
July 2000
Intermediate to advanced content levelIntermediate to advanced
1104 pages
35h 1m
English
O'Reilly Media, Inc.
Content preview from Programming Perl, 3rd Edition

Logical and, or, not, and xor

As lower precedence alternatives to &&, ||, and !, Perl provides the and, or, and not operators. The behavior of these operators is identical--in particular, and and or short-circuit like their counterparts, which makes them useful not only for logical expressions but also for control flow.

Since the precedence of these operators is much lower than the ones borrowed from C, you can safely use them after a list operator without the need for parentheses:

unlink "alpha", "beta", "gamma"
        or gripe(), next LINE;

With the C-style operators you'd have to write it like this:

unlink("alpha", "beta", "gamma")
        || (gripe(), next LINE);

But you can't just up and replace all instances of || with or. Suppose you change this:

$xyz = $x || $y || $z;

to this:

$xyz = $x or $y or $z;    # WRONG

That wouldn't do the same thing at all! The precedence of the assignment is higher than or but lower than ||, so it would always assign $x to $xyz, and then do the ors. To get the same effect as ||, you'd have to write:

$xyz = ( $x or $y or $z );

The moral of the story is that you still must learn precedence (or use parentheses) no matter which variety of logical operators you use.

There is also a logical xor operator that has no exact counterpart in C or Perl, since the only other exclusive-OR operator (^) works on bits. The xor operator can't short-circuit, since both sides must be evaluated. The best equivalent for $a xor $b is perhaps !$a != !$b. One could also write !$a ^ !$b or even ...

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.
Start your free trial

You might also like

Mastering Perl, 2nd Edition

Mastering Perl, 2nd Edition

brian d foy
Programming the Perl DBI

Programming the Perl DBI

Tim Bunce, Alligator Descartes
Perl in a Nutshell, 2nd Edition

Perl in a Nutshell, 2nd Edition

Nathan Patwardhan, Ellen Siever, Stephen Spainhour

Publisher Resources

ISBN: 0596000278Supplemental ContentErrata