Perl Programming Page 6 - Perl 101 (Part 2) - Of Variables And Operators |
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 = 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 = 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 = This article copyright Melonfire 2000. All rights reserved.
blog comments powered by Disqus |