Perl: some explanation of yesterday’s while loop

The tutor explains a few details about yesterday’s program.

The program, with the while loop and its support code added in orange, is as follows:

#!/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 first orange line,
$prov=’Y’;
is needed because the while loop is about to check the value of $prov. If the value of $prov is “not equal to” (which is what ne means) ‘X’ or ‘x’, the program enters the while loop. To make sure that, on the first pass, $prov ne ‘X’ && $prov ne ‘x’, we set $prov=’Y’. (&& means “and”).

Next, we enter the while loop body. The reddish-brown lines of code are likely self-explanatory to people who have read my other posts about Perl programming. Then, we come to the orange
if($prov eq ‘X’ || $prov eq ‘x’){
next;
}

This if test checks if $prov is equal to (which is what eq means) ‘X’ or ‘x’. (|| means “or”.)

If indeed $prov eq ‘X’ || $prov eq ‘x’, we enter the if body, where we reach the single instruction next. The next instruction kicks the program back up to the top of the while loop, where $prov fails the $prov ne ‘X’ && $prov ne ‘x’ condition. The program bypasses the while loop to the last line of the program, and prints out

Thanks for playing:)

As long as the user doesn’t enter X or x, the program continues offering the game. The while and if conditions check the value of $prov to know when the user desires to exit.

I’ll be saying even more about the ideas mentioned here. In the meantime,
HTH:)

Sources:

Robert’s Perl tutorial

McGrath, Mike. Perl in easy steps. Southam: Computer Step, 2004.

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Leave a Reply