Previous Table of Contents Next


Exercise 5

Difficulty: Easy

Write a program that uses foreach and += to print the sum of an array of numbers. Test it with the first hundred positive integers (1..100), which sum to 5050.

Session 6
Advanced Loops

We’ve covered two types of loops so far: foreach and while. In this session, you’ll learn about the other commonly used loop statement in Perl: for, as well as three loop operators (next, last, and redo) that allow you to exert finer control over the sequence of execution.

The for Loop

Perl’s for loop is just like C’s for loop—it lets you specify an event that occurs after every loop iteration and what happens before your loop begins (Figure 1-9). for doesn’t do anything that a while loop can’t do—it just does it more concisely.


Figure 1-9  The for loop


The for Loop
for(START; STOP; ACTION) { BODY } initially executes the START statement and then repeatedly executes BODY, as long as the STOP condition remains TRUE. The ACTION statement is executed after each iteration.

Unlike C, the curly braces are mandatory.

Listing 1-14 shows an example that uses a for loop to print the first ten letters of the alphabet.

Listing 1-14 alphabet: Using a for loop

#!/usr/bin/perl -w
for ($letter = ‘a’; $letter lt ‘k’; $letter++) {
    print $letter;
}

The for loop first sets $letter to a and then checks to make sure that the stop condition is satisfied. It is—a is less than k—so it prints $letter. Then it performs the increment statement: $letter++. Now $letter is b and the loop begins again. This continues until $letter becomes k, at which time the loop exits.

        % alphabet
RESULT: abcdefghij

Listing 1-15 shows another tickets program that prints a list of movies, asks users to choose movies from the list, and then repeats those choices. It uses one for loop for each of the three tasks.

Listing 1-15 tickets4: Some for loops

#!/usr/bin/perl
@movies = (‘Casablanca’, ‘E.T.’, ‘Star Wars’, ‘Home Alone’);y
@choices = ();                     # An empty array for
                                     storing user choices.

# Start $i at 0, and loop through 3, incrementing by 1 each time,
# and printing the $ith element of @movies.
for ($i = 0; $i <= 3; $i++) {
    print “Movie number $i is $movies[$i] \n”;
}

print “\nHow many people are in your party? ”;
chomp($num = <>);

# Start $i at 1, and loop through $num, incrementing by 1 each time,
# and pushing the user’s choice onto the end of @movies.
for ($i = 1; $i <= $num; $i++) {

    print “What movie would you like to see, person #$i? ”;
    chomp($choice = <>);
    push(@choices, $choice);
}

print “\nFor your party of $num:\n”;

# Start $i at 0, and loop through $num - 1, incrementing by 1 each time,
# and printing which movies people want to see.
for($i = 0; $i < $num; $i++) {   # Count from 0 to $num-1
    print ‘Person ’, $i+1, “ would like to see $movies[$choices[$i]]. \n”;
}

A sample session:

        % tickets4
RESULT: Movie number 0 is Casablanca
        Movie number 1 is E.T.
        Movie number 2 is Star Wars
        Movie number 3 is Home Alone

        How many people are in your party? 3
        What movie would you like to see, person #1? 2
        What movie would you like to see, person #2? 0
        What movie would you like to see, person #3? 3

        For your party of 3:
        Person 1 would like to see Star Wars.
        Person 2 would like to see Casablanca.
        Person 3 would like to see Home Alone.

Let’s examine each for loop in turn. The first loop is the simplest.

for ($i = 0; $i <= 3; $i++) { print “Movie number $i is $movies[$i] \n”; }

First the start statement is executed: $i = 0.

Then $i is compared to 3. It’s less than or equal to 3, so the block is executed.

Then $i is incremented and the loop begins again.

The second loop is similar to the first, except that $i starts at 1 instead of 0 and the stop condition depends on the value of $num instead of being fixed at 3. If there are four people in the party, the loop is executed four times.

The third for loop starts $i at 0 and continues until $i is no longer less than $num. Both the second and the third loops execute $num times—but there’s a difference: The second loop counts from 1 to $num, whereas the third loop counts from 0 to $num-1.


Previous Table of Contents Next