Modifiers

Any simple statement may be followed by a single modifier that gives the statement a conditional or looping mechanism. This syntax provides a simpler and often more elegant method than using the corresponding compound statements. These modifiers are:

                     statement if EXPR;
statement unless EXPR;
statement while EXPR;
statement until EXPR;

For example:

$i = $num if ($num < 50); # $i will be less than 50
$j = $cnt unless ($cnt < 100); # $j will equal 100 or greater
$lines++ while <FILE>;
print "$_\n" until /The end/;

The conditional is evaluated first with the while and until modifiers except when applied to ado {} statement, in which case the block executes once before the conditional is evaluated. For example:

do {
    $line = <STDIN>;
    ...
} until $line eq ".\n";

For more information on do, see Chapter 5.

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.