4.3. The while/until Statement

No programming language would be complete without some form of iteration[2] (repeated execution of a block of statements). Perl can iterate using the while statement:

while (some_expression) {
    statement_1;
    statement_2;
    statement_3;
}

[2] That's why HTML is not a programming language.

To execute this while statement, Perl evaluates the control expression (some_expression in the example). If its value is true (using Perl's notion of truth), the body of the while statement is evaluated once. This is repeated until the control expression becomes false, at which point Perl goes on to the next statement after the while loop. For example:

print "how old are you? ";
$a = <STDIN>;
chomp($a);
while ($a > 0) {
    print "At one time, you were $a years old.\n";
    $a--;
}

Sometimes it is easier to say "until something is true" rather than "while not this is true." Once again, Perl has the answer. Replacing the while with until yields the desired effect:

until (some_expression) {
    statement_1;
    statement_2;
    statement_3;
}

Note that in both the while and the until form, the body statements will be skipped entirely if the control expression is the termination value to begin with. For example, if a user enters an age less than zero for the program fragment above, Perl skips over the body of the loop.

It's possible that the control expression never lets the loop exit. This is perfectly legal, and sometimes desired, and thus not considered an error. For example, you might want ...

Get Learning Perl, Second 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.