Internet

Beginning CGI Programming with Perl

Exercise 3.3. The Perl loop statements While and Until

In Perl, as in other languages, you actually can build more than the basic looping constructs, but the four basic loop constructs will satisfy all your programming needs. Even these four do basically the same thing:

  1. Checks for some condition
  2. If True, executes the next block of statements
  3. Repeats from step 1

You will find yourself using at least two of the four constructs on a regular basis. It’s kind of like the different knifes you have in your kitchen. They all do basically the same thing, but you use different knifes to do slightly different tasks. The four basic loop control structures follow:

while (conditional expression) {block of statements}until (conditional expression) {block of statements}for (conditional expression) {block of statements}foreach variable (array) {block of statements}

There is a fifth construct that really isn’t a loop control construct but sometimes is used with loops to change when the conditional expression is evaluated. This fifth construct is called the do statement. In this exercise, you will learn about the while and until loops and the effect the do statement has on these two loop constructs.

The while and until loop constructs first check the conditional expression before they execute their block of statements. The do statement has the following syntax:

1:  do {block of statements} while (conditional expression)2:  do {block of statements} until (conditional expression)

This makes the do looping constructs unique among the other looping constructs. The do until/while loop construct always executes the {block of statements} at least once. The (conditional expression) of the while/until statement is evaluated after the {block of statements} of the do statement. Each of the other loop control constructs evaluate the (conditional expression) first and might not ever execute their {block of statements}. The for and foreach statements are covered in the exercises in Tutorial 4. Listing 3.10 illustrates using the while, until, and do statements using different looping variations.


Listing 3.10. Using the Perl while and until loops.

01: #!/usr/local/bin/perl02:03: while($count < 5){04:     print "the count is $count\n";05:     $count++06: }07:08: print "The count AFTER THE WHILE is now $count\n";09:10: until ($count > 9) {11:     print "the count in the until loop is $count\n";12:     $count++;13: } ;14:15: print "The count AFTER THE UNTIL is now $count\n";16:17: do {18:     print "the count in the do while loop is $count\n";19:     $count++;20: } while ($count < 9);21:22: print "The count AFTER THE DO WHILE is now $count\n";23:24: do {25:     print "the count in the do until loop is $count\n";26:     $count++;27: } until ($count > 14);28:29: print "The count AFTER THE DO UNTIL is now $count\n";30:31: while(@pwdlist = getpwent){32:     $user = $pwdlist[0];33:     $shelltype = $pwdlist[8];34:     print "$user uses the $shelltype shell\n";35: }

In Perl, the while loop generally is used for reading files, as illustrated on line 31, but I think it’s easier to understand what is happening with the four examples before line 31, so that’s why you’re working with them right now.

Because Perl creates your variables for you as you need them, the conditional expression on line 3 will work as expected. In other languages, using a variable before setting it creates problems. In other languages, the variable might have unknown data in it, which could result in a very large number being in $count before it is used. Perl tries to be helpful and deals with initializing the $count variable to 0 and then increments it by 1 on line 5. If you want to practice safe programming, I recommend inserting this line before line 3:

$count = 0;

Initializing data is like having safe sex: You don’t really see the results for the extra work, except in the bugs you don’t get in your code. The opposite is also true. Not initializing your data is like unprotected sex: You can usually get away with it, but when you don’t, you really regret it. You could spend hours picking the bugs out of your code only to find that your program is fine except for some corrupted initial data.

The while and until loops starting on lines 3 and 10, respectively, operate in a similar manner. First, the computer checks the conditional expression; if it evaluates to True, the {block of statements} is executed. Line 4 prints the value of counter ($count). Line 5 adds 1 to whatever was the previous value of $count. This is called incrementing the loop control variable. $count is called the loop control variable because the loop {block of statements} is executed only if $count passes the test of the conditional expression.

The syntax of line 5 might look a little strange to you. It also could be written as

$count = $count +1;

This could be read as take the current value in $count, add 1 to it, and then store the result back in the $count variable.

The syntax

$count++;

is shorthand for the longer assignment statement. You will see lots of code that uses the $count++ syntax, however, so it’s a good idea to get used to it early in your programming experience.

Let’s go back over the while and until statements. The computer always first checks the conditional expression after the while or until statement and then executes the {block of statements} if the conditional expression evaluates to True. After executing the {block of statements}, the computer returns to the while/until conditional expression and repeats the procedure of checking the conditional expression and executing the {block of statements} if the conditional expression is True. If the conditional expression evaluates to False, the computer skips the {block of statements} and executes the first line after the block of statements.

The while and until statements work exactly the way you would expect them to. If you use the while statement, the {block of statements} executes while the conditional expression is True-in this case, while $count is less than 5. If you use the until statement, the {block of statements} executes until the conditional expression is True-in this case, until $count is greater than 9.

The do while construct on lines 17-20 operates slightly differently. Because the {block of statements} follows the do statement instead of the conditional expression, the {block of statements} always executes at least once.

When you run this example, your computer prints $count equal to 10 after the until loop on lines 10-13. The until loop executes until $count is equal to 10 (greater than 9). Even though $count is obviously greater than 9, the computer first executes lines 17-19. The value of $count is printed on line 18 and then incremented on line 19. The conditional expression finally is evaluated on line 20 when $count now equals 11. The conditional expression evaluates to False and the computer moves onto the next statement on line 22. Lines 24-27 operate in a similar manner, except that the conditional expression does not immediately evaluate to False.

Most Perl programmers are used to seeing while loops that look like the example shown on lines 31-35. The conditional expression reads a line from the system password file and assigns the result of each line to the password list array. The function getpwent()returns an empty list after it has read every line from the password file, and the while loop conditional expression then evaluates to False.