O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

9.6. && and || as Control Structures

These look like punctuation characters or parts of expressions. Can they really be considered control structures? Well, in Perl-think, almost anything is possible, so let's see what we're talking about here.

Often, you run across "if this, then that." We've previously seen these two forms:

if (this) { that; } # one way
that if this;       # another way

Here's a third (and believe it or not, there are still others):

this
				 && that;

Why does this work? Isn't that the logical-and operator? Check out what happens when this takes on each value of true or false:

  • If this is true, then the value of the entire expression is still not known, because it depends on the value of that. So that has to be evaluated.

  • If this is false, there's no point in looking at that, because the value of the whole expression has to be false. Since there's no point to evaluating that, we might as well skip it.

And in fact, this is what Perl does. Perl evaluates that only when this is true, making it equivalent to the previous two forms.

Likewise, the logical-or works like the unless statement (or unless modifier). So you can replace:

unless (this) { that; }

with:

this
				 || that;

If you're familiar with using these operators in shell programming to control conditional execution commands, you'll see that they work similarly in Perl.

Which one should you use? It depends on your mood, sometimes, or how big each of the expression parts are, or whether you need to parenthesize the expressions ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required