Altering Control Flow

There are often programming situations where you need to perform a lookup within a data structure such as an array. You either find the item for which you conducted the search or you do not. Once you have found the item, you need to exit from the search loop. There are other situations where you also may need to alter control flow from within a loop.

last

The program below reads a list of hotels from a file. The user is then asked to enter the name of a hotel. The program loops through the list of hotels, trying to find the user's input among the hotels from the file. See the folder Hotels.


% type hotels.pl
#
# hotels.pl
#
open(HOTELS, "hotels");
@hotels = <HOTELS>;
while(1)
{
        print "enter hotel name ";
        $hotel = <STDIN>;
        $found = 0;
        foreach $item (@hotels)
        {
                if ($item eq $hotel)
                {
                        $found = 1;
                        last;
                }
        }
        print "found $hotel
" if ($found)
}
%

In the inner loop above, if the hotel is found, the last statement sends control flow to the first statement beneath the loop in which last was executed.

next

On other occasions, you may wish to forego the rest of the statements in a particular loop in favor of the next iteration of the loop. This is a task for the next statement, which causes the next iteration of the loop to occur. Suppose we wanted to process only the positive numbers in an array. We could proceed as follows:

@numbers = (100, -30, 200, -40, 500);
foreach $number (@numbers)
{
        next if $number < 0;
        print "$number is positive
";
}

redo

Perl also has a redo statement. This allows you to redo the current iteration of a loop. You might use this in sequences such as in the following example. See the folder Grades.


% type grades.pl
#
#   grades.pl
#
print "How many grades? ";
chomp($grades = <STDIN>);
for ($i = 1; $i <= $grades; $i = $i + 1)
{
        print "Enter grade # $i: ";
        chomp($grade = <STDIN>);
        if ( $grade < 0 || $grade > 100 )
        {
                print "$grade is illegal
";
                redo;
        }
        $grades[$i - 1] = $grade;
}
print "Your $grades grades are: @grades
";
% perl grades.pl
How many grades? 3
Enter grade # 1: 85
Enter grade # 2: 120
120 is illegal
Enter grade # 2: 90
Enter grade # 3: 95
Your 3 grades are: 85 90 95
%

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

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