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.
Why do you need to know all this? Well, comparison operators come in very useful when building conditional expressions - and conditional expressions come in very useful when adding control routines to your code. Control routines check for the existence of certain conditions, and execute appropriate program code depending on what they find.
The first - and simplest - decision-making routine is the "if" statement, which looks like this:
if (condition)
{
do this!
}
The "condition" here refers to a conditional expression,
which evaluates to either true or false. For example,
if (bus is late)
{
con Dad into giving you a ride
}
or, in Perl language
if (bus_arrival == 0)
{
con_Dad();
}
If the conditional expression evaluates as true, all
statements within the curly braces are executed. If the conditional expression evaluates as false, all statements within the curly braces will be ignored, and the lines of code following the "if" block will be executed.
Here's a simple program that illustrates the basics of the "if" statement.
#!/usr/bin/perl
# ask for a number
print ("Gimme a number! ");
$alpha = ;
chomp ($alpha);
# ask for a different number
print ("Now gimme a different number! ");
$beta = ;
chomp ($beta);
# check
if ($alpha == $beta)
{
print("Can't you read, moron?
I need two *different* numbers!\n");
}
print("This is the last line! Go away now!n");
And they say that the popular conception of programmers as
rude, uncouth hooligans is untrue!
In addition to the "if" statement, Perl also allows you a couple of variants - the first is the "if-else" statement, which allows you to execute different blocks of code depending on whether the expression is evaluated as true or false.
The structure of an "if-else" statement looks like this:
if (condition)
{
do this!
}
else
{
do this!
}
In this case, if the conditional expression evaluates as
false, all statements within the curly braces of the "else" block will be executed. Modifying the example above, we have
#!/usr/bin/perl
# ask for a number
print ("Gimme a number! ");
$alpha = <STDIN>;
chomp ($alpha);
# ask for a different number
print ("Now gimme a different number! ");
$beta = ;
chomp ($beta);
# check
if ($alpha == $beta)
{
print("Can't you read, moron?
I need two *different* numbers!\n");
}
else
{
print("Finally! Someone with active brain cells!\n");
}
And here's another example, this time using strings - the
trigger condition here is the input string "yes".
#!/usr/bin/perl
# ask a question
print ("Did you like Austin Powers 2:
The Spy Who Shagged Me?\n");
$response = ;
chomp ($response);
# check
if ($response eq "yes")
{
print("Groovy, baby!\n");
}
else
{
print("Loser! May your soul rot in hell!\n");
}
This article copyright Melonfire 2000. All rights reserved.