Now that you've got the basics of the language down, this secondarticle in the series teaches you about Perl's variables and operators, andalso introduces you to conditional expressions.
Both the "if" and "if-else" constructs are great for black-and-white, true-or-false situations. But what if you need to handle the gray areas as well?
Well, that's why we have the "if-elsif-else" construct:
if (first condition is true)
{
do this!
}
elsif (second condition is true)
{
do this!
}
elsif (third condition is true)
{
do this!
}
... and so on ...
else
{
do this!
}
You can have as many "elsif" blocks as you like in this kind
of construct. The only rule is that the "elsif" blocks must come after the "if" block but before the "else" block.
#!/usr/bin/perl
# movie quote generator
# set up the choices
print("[1] The Godfather\n");
print("[2] American Beauty\n");
print("[3] The Matrix\n");
print("[4] The Usual Suspects\n");
print("[5] Casino\n");
print("[6] Star Wars\n");
print("Gimme a number, and I'll give you a quote!\n");
# get some input
$choice = ;
chomp($choice);
# check input and display
if ($choice == 1)
{
print("I'll make him an offer he can't refuse.\n");
}
elsif ($choice == 2)
{
print("It's okay. I wouldn't remember me
either.\n");
}
elsif ($choice == 3)
{
print("Unfortunately, no one can be told what the
Matrix is. You
have to see it for yourself. \n");
}
elsif ($choice == 4)
{
print("The greatest trick the devil ever
pulled was convincing the
world he didn't exist.\n");
}
elsif ($choice == 5)
{
print("In the casino, the cardinal rule is to keep
them playing and
to keep them coming back.\n");
}
elsif ($choice == 6)
{
print("I suggest a new strategy, Artoo:
let the Wookie win.\n");
}
else
{
print("Invalid choice!\n");
}
Depending on the data you input at the prompt, the "elsif"
clauses are scanned for an appropriate match and the correct quote is displayed. In case the number you enter does not correspond with the available choices, the program goes to the "else" routine and displays an error message.
This article copyright Melonfire 2000. All rights reserved.