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.5. Expression Modifiers

As Yet Another Way to indicate "if this, then that," Perl allows you to tag an if modifier onto an expression that is a standalone statement, like this:

some_expression if control_expression;

In this case, control_expression is evaluated first for its truth value (using the same rules as always), and if true, some_expression is evaluated next. This is roughly equivalent to

if (control_expression) {
    some_expression;
}

except that you don't need the extra punctuation, the statement reads backwards, and the expression must be a simple expression (not a block of statements). Many times, however, this inverted description turns out to be the most natural way to state the problem. For example, here's how you can exit from a loop when a certain condition arises:

LINE: while (<STDIN>) {
    last LINE if /^From: /;
}

See how much easier that is to write? And you can even read it in a normal English way: "last line if it begins with From."

Other parallel forms include the following:

exp2
				unless exp1; # like: unless (exp1) { exp2; }
exp2
				while exp1;  # like: while (exp1) { exp2; }
exp2
				until exp1;  # like: until (exp1) { exp2; }

All of these forms evaluate exp1 first, and based on that, do or don't do something with exp2.

For example, here's how to find the first power of two greater than a given number:

chomp($n = <STDIN>);
$i = 1;                 # initial guess
$i *= 2 until $i > $n;  # iterate until we find it

Once again, we gain some clarity and reduce the clutter.

These forms don't ...

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