Article

Programming Perl 101

Page: 1 2 3 4 5 6 7 8 Next

Next, enter this:

print "Content-type: text/html\n\n";

That tells the script that we might be using some HTML in our print commands…even if you don't use any HTML, I recommend using this line in your scripts at all times to avoid potential problems.

Now, enter this:

if ($action eq "1") {
print "You must have clicked the first button!";
}

It's not quite plain English, but it's a lot easier to understand that a lot of the other things in this tutorial. The above is called an "if" command. See the first line there? Translated into English, it would read "If the variable '$action' is equal to 1." Notice the opening bracket right after this statement, and the closing bracket after the print statement. Do you see where this is going?

The "if" statement is basically telling the script that if $action is equal to "1", then process the code inside those two brackets. If someone clicked, say, the second button, then the $action variable would equal something other than 1, and the code inside those brackets would not be processed - the script would simply skip over it.

Now, let's say you want to display some text in case someone presses the second button. Can Perl handle this? Heck yeah…enter this:

elsif ($action eq "2") {
print "Well, odds are you clicked the second button…";
}

The above code is fairly self-explanatory. It's like the "if" statement in every way, except we have an "els" in front of the "if." This, turned into a sentence, would read "Else if." This is telling the script that if the previous "if" statement is false (IE: if the equals condition is not met), then take a look at this statement, and if it equals "true" (if the $action variable equals 2), then process the code inside.

Creating a statement to display text if the user presses the third button is almost exactly the same:

elsif ($action eq "3") {
print "Who woulda thought? You pressed the third button!";
}

This is all well and good so far, but we need to have some sort of fail-safe. Using the code so far, a message will be displayed no matter which of the three buttons is pressed. But what if something else happens. For examples: what if the $action variable (nevermind the reason) equals something other than 1, 2, or 3?
Have no fear, there is a statement for this as well:

else {
print "Sorry, there is no page available for that number.";
}

A-ha! We can an "if" statement, two "else-if" statements, and now an "else" statement. The "else" statement is a last resort…if NONE of the first three conditions are met, the else statement is processed. It basically says "if none of the above statements need to be processed, process me." This makes sure that a message is displayed no matter what the $action variable equal.

Whew - learn enough yet? I didn't think so…keep reading.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links

Follow SitePoint on...