home about us contact us

free scripts advanced scripts online tools great books web related tutorials contributed tutorials news archive geek toys!

help forum live chat help

Putting a useful Perl program together, controlling the flow with: if/elsif/else conditionals.

So so far we know the following:

A variable is a placeholder for any string (of characters) or numbers.
Like so:

my $dog = 'rover';


my $number = 5;

An Array is a list of strings or numbers. that is numerically indexed (starting at zero).

my @array_of_animals = ( 'Dog', 'cat', 'horse', 'mouse', 'sheep', 'cow');

And a Hash or associative array, is a list of strings indexed by whatever keys you choose to give it. eg:

my %weekdays = (
  "Sun" => "Sunday",
  "Mon" => "Monday",
  "Tue" => "Tuesday",
  "Wed" => "Wednesday",
  "Thu" => "Thursday",
  "Fri" => "Friday",
  "Sat" => "Saturday",

So we have our data placeholders, now we need to know what to do with them..

The most common flow control in a Perl program (or any other lanuguage for that matter) is the if/elsif/else conditional statements. This allows you to set a series of conditions and based on the values of variables or some other testable condition, you can direct the way the program acts.

Here is an example of an if/elsif/else statement in use within a simple program.
(Incidently, elsif is not a typo, thats really how they spell it in Perl).


use CGI::Carp qw(fatalsToBrowser);
use strict;
use warnings;
use diagnostics;

# Now tell the server to send html to the browser:
print "Content-type: text/html\n\n";

# Set the $animal variable to whatever you
# Want to see the flow of the program.
my $animal = 'dog';

# an if statement:
if ($animal eq 'dog')
print "Your animal is a: \"$animal\"<br />\n";
print 'Woof Woof !!!!';

# elsif statement allows you do test for a
# different condition.
elsif ($animal eq 'cat')
print "Your animal is a: \"$animal\"<br />\n";
print 'Here pus,pus,pus,pus';

# you can have as many elsif statements as
# you like.
elsif ($animal eq 'horse')
print "Your animal is a: \"$animal\"<br />\n";
print 'Hello mr Ed!!!';
# Else statement catches anything that
# didn't match the first conditions.
print "I have no idea what an \" $animal \" is<br />\n";
print 'Sorry I can\'t be of more help.';

Later, I will show you how to use cgi to ask the user what their animal is instead of having it fixed in the code as dog like it is now.
(The line that is setting it fixed as dog now is: my $animal = 'dog';)

This little program introduces allot of new stuff.
firstly, notice the \n near the end of each line?? that is the symbolic meaning of "newline" which means Perl is bacically pressing return everywhere you see the \n. in this case, it will stop the source in your browser from being all on one line.. but since we know that HTML doesn't care if the source is on one line or not when it comes time to render, we have to use <br /> to get the browser to go to the next line when showing the HTML. (or <p> or whatever HTML you like...)

Next thing, notice that sometimes I have used double quotes around statements, and other times single quotes? Thats very observant of you. :-). There is a good reason for that, and its called interpolation.

Single quotes are the default, you should always use single quotes unless there is a reason not to.. In one of the examples above, you see this : print "you animal is a: \"$animal\"<br />\n"; I used double quotes because I want the variable $animals in that line to be replaced with the value of $animals set at the top of the script, if I had used single quotes, it would have left $animal as exactly that, $animal, instead of dog, (or cat, or horse etc..) (also notice the \" before and after the $animal, Since I want those dbl commas to be displayed and not interpreted by Perl, I tell Perl to ignore them by putting a \ in front of them. (the same way that putting a \ in front of n turns it from the character n into a newline.))

The reason single quotes are the default, is for a couple of very good reasons.
1. If you don't have to do any interpolation, then why make Perl work harder looking for it? (if you put it in double quotes, Perl will go looking for things to replace (otherwise known as interpolating variables).)
2. Using single quotes means you don't have to excape characters you otherwise would have to. (I'll explain more on that later, but really, the only thing you have to escape when using single quotes, is a single quote itself.. (like in the second last line in the word "can't" otherwise Perl would assume that line was 'Sorry I can' and then generate an error when if tried to work out what: t be of more help.' was, (because it only one single quote, its not enclosed by quotes...)

Lastly, we will cover the if/elsif/else statements thenselves.

if (In here goes a test of some sort)
   # Do something if the above test is true.

elsif (The first test wasn't true, so try this new test)
   # Do something here if the second test returned true.

   # Do this is neither of the above tests returned true.

Thats pretty basic, so I don't think it requires much explanation...
one last thing I just noticed that I should mention..
You may have noticed up the top of that script I said:

$animal = 'dog'; 

And then in the if statements, I tested by using eq instead of = ???
There is a good reason for that, if I had tested by saying

if ($animal = 'dog')

I'd have just set the variable $animal to equal dog, which is not what I wanted to do at all (we were testing the value, not setting it).

Incidently, we do use = for testing variable values, but we only use it with numeric values and then we use two equals signs not one. (as shown above) If we only used one, we'd be changing the value rather than testing it.

# These will always return true.
# because you've set $animal equal to dog,
# or $mynum equal to 3
# and a successful assignation will return true.
if ($animal = 'dog')
if ($mynum = 3)

So the correct way to do these if tests, is like so:

# Both correct tests of string and numeric values..

     # Test of string value
  if ($animal eq 'dog')
     # Test of numeric value
  if ($mynum == 3)

These are not the only program flow controls that Perl has available, there is also:

unless (some test statement)
# Do whatever is here "unless" the above statement is true.

There are also for/foreach loops, and "while" conditionals as well, all of which will be discussed in future tutorials.
As you see examples of these in practise, it will all start to make sense and fit together and you will find yourself wondering why it seemed confusing when you started.
(assuming that you currently find it alittle confusing :-).

So if you are ready to learn more:
Back to the Tutorial Index