Perl 101 (Part 3) - Looping The Loop - Dos And Don'ts (
Page 4 of 9 )
The two control structures explained above test the conditional expression
first, and only proceed to execute the statements within the loop if the
expression evaluates to true. However, there are often occasions when you
need to execute a particular set of statements at least once before you
check for a valid conditional expression.
Perl has a solution to this problem too - it offers the "do-while" and
"do-until" constructs, which allow you to execute a series of statements at
least once before checking the conditional expression. Take a look:
do {
do this!
} while (condition)
or
do {
do this!
} until (condition)
In this case, Perl will only test for the condition *after* executing the
loop once.
#!/usr/bin/perl
# weighted employee evaluation program version 2.0
# call me WEEP II!
# use DO to ensure that the statements
# within the loop are executed at least once
do {
print ("Can we put you in a cubicle, cancel all your benefits, and pay
you less than minimum wage? [y/n] ");
$reply = <STDIN>;
chomp($reply);
} while($reply ne 'y');
print ("Heh heh! This company couldn't do without employees like you!\n");
As you can see, the "do" construct can help to make your code more compact
- compare WEEP version 2.0 with the original above.
This article copyright Melonfire 2000. All rights reserved.