while Loops

The various if statements in Perl are all used to control execution by branching to differ-ent parts of a script. The second way to control execution is through the use of a loop, where the same block of Perl statements are executed repeatedly, stopping only when some condition is met. Perl has two general sets of loops, both of which do roughly the same thing: while loops, which loop until a condition is met, and for loops, which loop a certain number of times. Generally, whiles can be rewritten to emulate fors, and vice versa, but conceptually each one seems to lend itself to specific situations better than the other.

We'll start with the while loops, of which Perl has three: while, dowhile, and until.

while

You've already seen the while loop, but we'll repeat the description here so you have it all in one place. The basic form of the loop in Perl is the while, which takes a test and block, like this:

while ( test ) {
   # statements to loop
}

In the while loop, the test is evaluated, and if it's true, then the statements inside the block are executed. At the end of the block, the test is evaluated again, and if it's still true, then the block is executed again. This process repeats until the test returns false. For example, here's the while loop from the cookie script you saw on Day 1:

while ( $cookie ne "cookie") {
  print "Give me a cookie: ";
  chomp($cookie = <STDIN>);
}

Here, the prompt and input will repeat until the input actually matches the string "cookie". You could read this statement as “while the value of $cookie doesn't equal the string 'cookie', do these things.”

Here's another example from Day 4 that loops through an array using an temporary variable $i as the array index:

$i = 0;
while ($i <= $#array) {
   print $array[$i++], "
";
}

In this case, the test is whether $i is less than the largest index of the @array array. Inside the block, we print the current array element, and increment $i, so that the loop will only repeat a certain number of times: while $i is less than or equal to the largest index in @array, actually.

Remember as you write your while loops that something has to happen inside the loop to bring the state of the loop closer to exiting. If you forget to increment $i, $i will never reach a point where the test is true, and the loop will never exit.

Loops that don't exit are called infinite loops, and sometimes they're useful to use intentionally. A while loop without a test, for example, is an intentional infinite loop. You've seen these in a number of the examples we've done so far. This one's from the various statistics scripts:

while () {
  print 'Enter a number: ';
  chomp ($input = <STDIN>);
  if ($input eq '') { last; }

  # more stuff to do
}

This loop will read a line of input from the standard input at each pass of the loop, and will never exit based on the test at the top of the while—there is no test inside the parentheses after the while. But we do test the input in an if conditional three lines down, and if the $input doesn't match our test there (if it's equal to the empty string), then the last; keyword will forcibly break the loop and go onto the next part of the script. The last part is a form of loop control statement, and there are three of them: last, next, and redo. You'll learn about these later in this chapter, in the section, “Controlling Loops.”

I could have rewritten this loop so the while had a real test, and exited at the appropriate time. For this particular type of example, I found it easier to construct it this way. Perl doesn't enforce a specific kind of mindset for creating loops or conditionals; you can construct your script in the best way based on how you see the problem.

until

Just as the reverse of an if is an unless, the reverse of a while is an until. Until looks just like a while, with a test and a block:

until ( test ) {
   #  statements
}

The only difference is in the test—in a while, the loop executes as long as a test is true. In an until, it executes as long as the test is false—“until this test is true, do this stuff.” Otherwise, they both behave the same.

do

A third form of while loop is called the do. With both while and until, the test is evaluated before the block is executed—so, actually, if the test ends up being false (or true for unless), then the block won't get executed and the loop might never do anything. Some-times you want to execute some block of statements, and then try the test afterwards. That's where do comes in. do loops are formed differently from while and until loops; unlike the former, they require semicolons at the end of the statement. do loops look like this:

do {
   # block to loop
} while (test);

Or, with until, same idea:

do {
   # ...
} until (test);

With either of these statements, the statements inside the block are always executed before the test is evaluated. Even if the test returns false (for while) or true (for until), the block of statements will be executed at least once.

One important thing to note about the do: do in this case is actually a function call pretending to be a loop (that's why you need the semicolon). In most basic cases, it'll perform just like a loop, but if you want to use loop controls inside it (such as last or next), or include a label, you'll have to use either while or until instead. More about loop controls and labels later.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.156.122