Perl: while loop
This application of the while loop has been long coming.
Yesterday’s program, in which the user can indicate a Maritime province and be told its capital, has one drawback: it exits after giving the answer. What if the user wants to be given the capitals of other Maritime provinces? The user needs to recall the program each time. Although not difficult, it’s not convenient.
With a while loop, the user can be invited to play the game over and over again until they decide to stop.
Let’s look at yesterday’s program with a while loop added. There are a few other additions to support the while loop. The new code is in orange:
#!/usr/bin/perl
%maritimecapitals=(‘NB’,’Fredericton’,’NS’,’Halifax’,’PEI’,’Charlottetown’);
$prov = ‘Y’;
while($prov ne ‘X’ && $prov ne ‘x’){
print “Hello. Which Maritime capital would you like to know?\n\n”;
print “Key in NS for Nova Scotia, NB for New Brunswick, or\n\n”;
print “PEI for Prince Edward Island.\n\n”;
$prov=<STDIN>;
chomp $prov;
if($prov eq ‘X’ || $prov eq ‘x’){
next;
}
print “The capital of $prov is $maritimecapitals{$prov}.\n\n”;
}
print “Thanks for playing :)\n\n”;
The while condition checks the value of $prov to see if it’s ‘X’ or ‘x’.
If it is, the program bypasses the code inside the while loop and prints out Thanks for playing:)
Inside the loop, the value of $prov must be checked again because the user freshly enters it. The code is there, but I’ll explain it next time, along with a few other details.
HTH:)
Sources:
McGrath, Mike. Perl in easy steps. Southam: Computer Step, 2004.
Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.
Leave a Reply
You must be logged in to post a comment.