Perl: the if, [elsif], else construction

Tutoring computer science, this topic is fundamental.  The tutor gives a short program as a focal point.

 
Back in my last post I introduced the if, else construction. Today we’ll look at a sample program that implements it.

Let’s imagine that your (geeky) spouse has written a grocery list into a Perl array. However, you don’t know if she’s included olive oil. You write a little program to read the array, then report if “olive oil” is present.

One extra parameter: your spouse likes to abbreviate. Therefore, she might have written “olive o.” for “olive oil.”

Here’s the program. Note that the comments are in green.

#!/usr/bin/perl

#for our purposes, you might imagine you can’t see the
#contents of @groceries

@groceries=(“butter”,”sugar”,”bread”,”eggs”,”deli ham”,”cheddar cheese”,”olive oil”,”coffee”,”oranges”,”apples”,”grapes”,”olive o.”,”milk”,”cream”);
$i=0;
while($groceries[$i]){
if($groceries[$i] eq “olive oil”){
print “Olive oil is element $i in the list.\n”;
}
elsif($groceries[$i] eq “olive o.”){
print “Olive o. is element $i in the list.\n”;
}
else{
print “Not element $i\n”;
}
$i++;
}

Let’s imagine this program is called groclist.txt. On the command line, in its proper directory, you’d run it by keying in

perl groclist.txt

Assuming no typos (by me or you), you might be greeted with the following output:


Not element 0
Not element 1
Not element 2
Not element 3
Not element 4
Not element 5
Olive oil is element 6 in the list.
Not element 7
Not element 8
Not element 9
Not element 10
Olive o. is element 11 in the list.
Not element 12
Not element 13


The details of this program I’ll explain next post. Cheers:)

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

Leave a Reply