Perl Conditionals - You Better or Else! (Page 2 of 4 )
Part of being a rich, illustrious writer is bossing people around. Many times throughout the day I will berate the employees around me, sending them scurrying for cover. [Well, you can dream. --Ed.] When they don't do what I like or want, I give them an If Statement with an Else clause.
#!/usr/bin/perl
$do_my_bidding = 'Yes Master!';
if ($do_my_bidding = 'Yes Master!'
{
print "You are a good slave. Tell your mother I will see her tonight";
}
else
{
print "You ignorant buffoon! Tell your mother I will see her on my lunch break!";
print "Get out of my sight!";
In the above code, if $do_my_bidding holds the value, "Yes Master!" you will get the following result:
You are a good slave. Tell your mother I will see her tonight.
Get out of my sight!
If the value of $do_my_bidding held any other value, you would see this:
You ignorant buffoon! Tell your mother I will see her on my lunch break!
Get out of my sight!
No matter which condition is met, the program will always print: Get out of my sight!, as it is not part of either conditional.
Elsif
Sometimes one Else clause is not enough. That's where Elseif comes in handy. Observe!
#!/usr/bin/perl
$do_my_bidding = 'Yes Master!';
{
print "You are a good slave. Tell your mother I will see her tonight";
}
elsif ($do_my_bidding = 'No')
print "Insolent swine! Tell your mother to come right now!";
else
{
print "You ignorant buffoon! Tell your mother I will see her on my lunch break!";
print "Get out of my sight!";
Again, with the above code, if the value of $do_my_bidding is "Yes Master!" it will result in:
You are a good slave. Tell your mother I will see her tonight.
Get out of my sight!
If the value of $do_my_bidding is "No" the following would print to your screen:
Insolent swine! Tell your mother to come right now!
Get out of my sight!
And finally, if the value of $do_my_bidding is anything else, it will print:
You ignorant buffoon! Tell your mother I will see her on my lunch break!
Get out of my sight!
You will note two things: 1) The phrase "Get out of my sight!" is always printed as it is outside of the statements. And 2) No matter what you say, I am still going to spend some time with your mother. It's simply a matter of when.
Next: The Unless Statement >>
More Perl Articles
More By James Payne