Loops #2

#0 | #1 | #2 | #3 | #4

while

This is a very useful loop statement. Use it whenever you can't use a foreach or for loop. For example, when you don't know when to terminate the loop. Your block of statements gets executed as long as the condition is true.

Here we start with $5.00 and increase it by $1.00 each time through the loop.

We've seen the auto-increment operator on a previous page on strings.

my $money = 5;
while ($money <= 12) {
    print "You now have " . $money++ . " dollars\n";
}

This seems pretty easy to understand - print the value of $money while it is less than (or equal to) $12.00; then add $1.00; test it again.

Here is what happens if we increment it first (++$money), then print it:

Depending on your particular situation, choose the right operator for your needs.

while,continue

That's not all there is to a while loop. We can execute code after each time through the loop using continue.

my $ndx = 1;
while ($ndx <= 5) {
    print "$ndx\n";
} continue {
    $ndx++;
    print "\tHow many was that?\n";
}

As you may see, this is very useful if you want to execute some code after each iteration - even if you don't execute the full body of the loop.

do,while

Perl doesn't actually have a do while loop - but there is a do statement, which happens to work just fine with a while loop.

And used with while it works exactly like a do while loop. Confused yet?

my $i = 10;
do {
    print " $i: I can't do all this\n";
    $i++;
} while ($i < 5);

This example requires some thought. $i is set to 10. In the do loop $i is incremented. The while condition looks for $i < 5. But the print statement is executed in the loop.

How many times does it print the statement?

Usually a condition in a statement modifier is executed BEFORE the statement, but in the do while construct, Perl provides an exception - the modifier is executed AFTER the statement.

In this example the print statement is executed once. Try it.

for

The for loop statement is used a lot since it is so versatile. Usually it is used when looping over an array, since it is indexed numerically. If you know the number of times you want to do something, this is the one to use.

We've briefly used this loop previously, but now we get up close and personal with it.

for (my $i=1; $i <= 7; $i++) {
    print "Hello # $i\n";
}

You should be able to readily understand what's going on here - just 'read' the code.

Note we can use the loop index $i in the loop body as well as in the conditional setup. This is how we walk through an array.

However, it is never a good idea to re-assign the value of the index loop inside a loop - LEAVE IT ALONE.


my @nums = (1,2,3,4,5,6,7);
my $sum = 0;
for (my $i = 0; $i <= $#nums; $i++) {
    $sum += $nums[$i];
}
print "Sum = $sum\n";

Which prints '28' as a result. More loop structures follow.