Perl Conditionals (Page 1 of 4 )
While Perl truly is the programming language of the slacker, the bored, and the (okay I'll say it with great lamentation) creative, it is also a harsh mistress. But let's face it: as a computer programmer, you are luck to have a mistress at all. So chin up. Perl doesn't just freely give you love. There are conditions, or, more precisely, conditionals, which is the topic of this fourth part in a series.
Sure, in the beginning, when you are learning syntax and how to print My cat is named Darth Fluffymittens, Perl is nice and easy, ready to go anytime you are. But as soon as you get to the part about Conditionals...bam! Marriage over.
Maybe I have written too many articles on conditionals; if there is a programming language, you can rest assured I told someone how to write conditionals in it. Maybe I am jaded. Perl conditionals, I have to admit though, are very simple once you grasp the concept.
So put on your safety gloves and let's get to grasping.
Conditional Lovin'
Conditionals are statements written in code that ask a question, and then respond accordingly to the answer. A good way to think of a conditional is to think about yourself when a bill is overdue. Yeah you slacker, I know all about your late bills.
In pseudo code (or fake code), the situation would look like this:
If
I pay bill
Then lights stay on
End
The above is an example of an If-statement. Simply put, do this, and this happens. Now let's see the same situation in real code:
#!/usr/bin/perl
$your_money = 0;
if ($your_money < 1) #asks if your money is less than 1
{
print "You are broke!"; #if it is, print "You are broke"
}
print "Your lights might be shut off!";
The above code asks if you have less than a dollar. If the answer is yes (which it is), then the program prints: "You are broke!". The last line: "Your lights might be shut off!" prints regardless of the conditional, as it is outside of the statement.
If the value of $your_money was greater than 1, the program would have skipped the "You are broke!" line but still printed the "Your lights might be shut off!" sentence.
Next: You Better or Else! >>
More Perl Articles
More By James Payne