Programming Perl 101

Share this article

1.) Background Information

If you run a website, you’ve probably heard of either Perl or CGI at some point. Whether you’ve merely heard of it, installed a few scripts on your own, or taken one look at the code and turned pale, this tutorial is for you.

Perl is a programming language. Many people think CGI is a language, as in, “I’m going to learn CGI,” but this is erroneous. Think of CGI as the method in which you use Perl. You can write CGI scripts using other programming languages, but Perl is far the most common due to its relative simplicity and power.

Even as more efficient programming languages are starting to take away Perl’s popularity, Perl programming remains very popular and learning it is not a waste of time. For example, PHP is similar to Perl in most respects. The syntax used is similar and a lot of the basics are somewhat the same. If you know Perl, you’ve got a huge head start at learning PHP, and a few other languages as well.

Although Perl may be less efficient than other programming languages like PHP or ASP, there are still infinitely more freeware and shareware scripts out there written in Perl than in any other language. In other words, Perl isn’t going away anytime soon.

2.) A Few Small Rules

Now that you have a little background on Perl, let’s get down to some of the basic commands.

Like any programming language, Perl has rules. You will need to use certain symbols in certain places to tell the script something. One of the most basic rules in Perl is that every line must end with a semi-colon: “;” . As with every rule there are a few exceptions which we’ll go into later, but for now just realize that almost every line of Perl code that you write will end with a semi-colon. The semi-colon, in case you’re wondering, tells Perl that it has reached the end of a command.

Let’s write a quick script to introduce you to some of the basics.

In any Perl-based script, a line like this goes at the very top:

#!/usr/local/bin/perl

This has been nicknamed the “shebang” line, and it is another requirement of the Perl language. The shebang line points the browser to the path to the Perl interpreter on your web host’s server. Think of this line as a way of telling your browser, “Here’s where you can find a translator to turn my code into a functional script.”

Virtually every web host has Perl installed, although it will not always be in the location specified above. If the above line doesn’t work, contact your system administrator and ask them for the path to Perl.

Note that you’ll need to point to the Perl interpreter in each and every file that you write. (Note: files that end in .cgi, .pl, and .perl can all be considered Perl files.)

This tutorial from now on assumes that you have a basic knowledge of HTML and form fields. If you don’t, head on over to http://www.HtmlGoodies.com and read through some of the tutorials offered there.

Let’s create our first script!

3.) Starting Off

The script we are about to create will take the information your user submits in a standard feedback form and then load a page showing him what he just entered. Not terribly useful, but a great example to get us started.

In this example, we’ll have someone enter their name, city, and favorite food (after all, that’s the basic vital information for all of us, right?).

First, we create the HTML page with the form:

<html>
<head>
<title>Submit Your Information</title>
</head>

<body>

<h1>Submit Your Information</h1>
<p>
<form action=”display.cgi” method=”post” >
First Name: <input type=”text” size=”30″ name=”first”><br>
City: <input type=”text” size=”30″ name=”city”><br>
Favorite Food: <input type=”text” size=”30″ name=”food”><br>
<P><input type=”submit” name=”submit” value=”Submit!”>
<input type=reset name=reset value=”Reset”>
</form>

</body>
</html>

Do you see the names of those form fields? Those are the identifying values assigned to each form field the user will be entering his information into. In this case they are “first,” “city,” and “food.” Think of the names given to form fields as containers that will hold the data entered by a user.

The way this works is that when a user enters their name into the appropriate form field, the name tag will “attach” itself to the data entered in order to identify it for later use. If a user were to enter the word “Marvin” into the “first” field, the word “Marvin” would be assigned the “first” tag. As you’ll soon see, we can use Perl to display whatever text has been given the “first” tag. Starting to make some sense?

Now, as you’ll notice, we have the form action set to “display.cgi.” This line in the form tells us that this information (with name tags attached, of course) will be sent to a certain file. In this case, display.cgi. Since, display.cgi doesn’t exist yet, let’s create it!

4.) Display.cgi

Now that we’ve got the form up (call the file whatever you like, just make sure that it has a .html or .htm extension) we’ll move onto creating the Perl script to work with the data. The way this entire thing will work is:

1. A user will view a form and fill out the data

2. Each field on the form and the data entered will have a name slapped to it

3. The data entered, together with the name of the form field, will be sent to display.cgi for processing

Let’s create display.cgi!

First, the shebang line:

#!/usr/local/bin/perl

Next, insert this:

require "subparseform.lib";
&Parse_Form;

Subparseform.lib is a widely used file that will aid us in the creation of this script. Do a search for it on the web and you should be able to find it. If your search fails, contact me and I’ll give you some help: mailto:chris@mycoding.com .

Now, remember: we want this script to take the information from the form and display it to the user in such a way as to say “This is the information you entered.” To do this we need to tell the script to “grab” the form information. But how? We simply have to match up those tags!

Enter this next:

$first = $formdata{'first};
$city = $formdata{'city'};
$food = $formdata{'food'};

Look familiar?

Take notice of a few things: first, the “;” sign is at the end of every line, as it should be. Second, the tag names: They match exactly with the tags on the form information.

Take note of the equals sign (“=”). That tells the script to assign the data entered into the form to a variable or container which we can use inside the Perl script. The first line is saying “make $first equal the information entered in the form field with the name ‘first'”.

As you’ve probably noticed, first, city and food have a dollar sign in front of them. Perl requires that all variables or containers used in a script begin with the $ sign.

That first line, as I said before, is telling the browser that whatever form field had the name of “first” in the HTML file, now has the name of “$first”.

What this allows us to do is use “$first” variable elsewhere in the Perl. What will happen is that $first will be replaced by whatever the user entered into the “first” field on the feedback form!

Starting to see where this is going?

Now, copy and paste this into the display.cgi file:

print "Content-type: text/htmlnn";
print "Thank you, here is the information you entered:<br>";
print "<ul><li>$first</li><li>$city</li><li>$food</li></ul>";

That first line tells the script that you’ll be using HTML in one or more of the “print” statements. Now that the information from the form has been assigned new variables beginning with the $ sign, all we have to do is type those variable names out and the script will display what the user entered.

The print statement that you see above simply tells Perl to spit out the HTML code out to the browser after parsing it. Here’s what Perl “thinks” when reading the above three lines:

Line One: Hmm… we’ll be working with HTML statements in one or more of the following print statements.

Line Two: Ok, this one is simple. I’ll just spit out the code between the quotation marks back out to the browser.

Line Three: This line contains three variables named $first, $city and $food that I need to find and replace before sending out this line of code to the browser. I’ll take the value of $first from the form field named “first” in the form that was just submitted to me, then I’ll do the same for $city and $food. Now that I know what $first, $city and $food stand for, I can send this line of code to the browser with the replacements made.

Here’s the entire display.cgi file:

#!/usr/local/bin/perl

require “subparseform.lib”;
&Parse_Form;

$name = $formdata{‘name’};
$city = $formdata{‘city’};
$food = $formdata{‘food’};

print “Content-type: text/htmlnn”;
print “Thank you, here is the information you entered:<br>”;
print ” – First Name: $first<br> – City: $city<br>”;
print ” – Favorite Food: $food”;

Let’s assume the user entered the name “John,” the city “New York,” and the favorite food as “Pizza.” Here’s what John would see displayed in front of him after filling out the form:

Thank you, here is the information you entered:
– First Name: John
– City: New York
– Favorite Food: Pizza

You should now have a basic grasp of some of the rules of Perl and how slapping identifying “tags” on data can be useful. As you’ll also learn later on, you can tell Perl to send out emails using these same variables (tags). Imagine having someone enter his email address and name, and getting an email personalized with his name in the subject line!

In Part 2 we’ll try to drill some syntax laws into your head, explore “if,” “elsif,” and “else” commands, and even explore using sendmail to send out automatic confirmation/thank you emails!

Welcome to Part two of this Perl Tutorial. In Part one, you were shown how a Perl script can take information submitted via an HTML and display the results back to the person submitting the form by making use of variables. Variables are the core of the Perl language, so today we’re going to learn a bit more about them.

1) Test.html

Create another HTML page and name it “test.html.” Put the following code onto the page:
<html>
<head>
<title>Test.html</title>
</head>

<body>
<form action=”http://www.yourdomain.com/cgi-bin/test.cgi” method=”post”>
<input type=”hidden” name=”action” value=”1″>
<input type=”submit” value=”Page 1″>
</form>
<br><hr><br>
<form action=”test.cgi” method=”post”>
<input type=”hidden” name=”action” value=”2″>
<input type=”submit” value=”Page 2″>
</form>
<br><hr><br>
<form action=”test.cgi” method=”post”>
<input type=”hidden” name=”action” value=”3″>
<input type=”submit” value=”Page 3″>
</form>
</body>
</html>

Don’t forget to substitute the form action URL with the path to your test.cgi file.

Notice the forms…they have only a submit button, and a “hidden” form field. This form field is obviously invisible to the visitor, however it can still hold a variable. If we click on the first button (labeled “Page 1”), it well pass the data along to the test.cgi file. Which data, you ask? Why, the data that says that the “action” field has a value of “2” of course! Using these values, we can tell the script to determine which button was pressed, and display the corresponding text and/or HTML.

Obviously the next step is to create the test.cgi file…let’s do that now.

2) Test.cgi

Create a text file and save it as “test.cgi”…as usual, you’ll need the subparseform.lib file uploaded to the same directory as test.cgi. As before, if you cannot find this through a web search, email me (chris@movieforums.com), and I’ll send it to you as an attachment.

On with things; enter this into test.cgi:
#!/usr/local/bin/perl
require "subparseform.lib";
&Parse_Form;
$action = $formdata{'action'};

As you can see, we have the standard shebang line first. Secondly, we have a command that makes sure that subparseform.lib is in the correct directory. Third, we have a subroutine (don’t worry about that word for now) that is being called to help us process the data being send from test.html, and fourth, we have a line that takes the value of the action field from test.html, and assigns it the variable “$action.”

Next, enter this:

print "Content-type: text/htmlnn";

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.

3) Sending email with Perl

Perl scripts, thankfully, have the ability to send email. Not only that, but the text inside the email and the address it is sent to can be specified using variables. You know what that means: users entering their email addresses, and receiving almost instant confirmation emails! Don’t worry, doing this is not at all. Create a file called email.html, and use this HTML inside of it:

<html>
<head>
<title>Signup Page</title>
</head>

<body>
<h3>Signup Today!</h3>
<form action=”http://www.yourdomain.com/cgi-bin/email.cgi” method=”post”>
<br>
<b>Email Address:</b> <input type=”text” name=”email”>
<br>
<input type=”submit” value=”Signup”>
</body>
</html>

Once again, don’t forget to substitute the form action URL with the path to your email.cgi file. Next, create a new text file, name it “email.cgi”, and enter this into it (the first few lines or so should look familiar):

#!/usr/local/bin/perl
require "subparseform.lib";
&Parse_Form;
$email = $formdata{'email'};

Alright, now we move into uncharted territory. Brace yourself:

open (EMAILS, ">>emails.txt");
flock(EMAILS, 2);
print EMAILS "$emailn";
flock(EMAILS, 8);
close (EMAILS);

Let’s take this one line at a time. The first line tells the script to open a file – emails.txt. If this file does not exist, Perl will create it on it’s own. If you plan to let Perl create the file, make sure your directory has the necessary permissions set. If you don’t know what I mean by directory permission, than just upload a blank text file named emails.txt to the same directory as email.html and email.cgi. The first line in the script also assigns the file a name: “EMAILS.”

The second like makes use of something called “file locking.” This is done to make sure that the file being opened does not change while the script is still processing this code. Imagine what could happen if someone made use of this script by trying to enter their information into emails.txt just as someone else is also doing the same thing? Which would go first? This leaves potential for corruption and a bunch of mixed up text.

File locking is obviously shortened here to “flock.” In this case, it is being used to make sure that no other script calling upon the emails.txt file will be allowed to open it for use until this script is doing using it, or until the file-locking command has ended.

Line three is simple: it prints whatever the user has entered in the “email” field into emails.txt, followed by a line break -represented here by a newline character: “n“.

Enter this next:

print "Content-type: text/htmlnn";
print "The email address '$email' has been successfully entered. ";
print "Thank you. You will receive a confirmation email shortly.";

Line four unlocks the emails.txt file for use elsewhere, and line five officially closes it. In case it isn’t obvious yet, so far, this script takes the email address entered by the user enters it into the emails.txt file, starts a new line, and does the whole thing over again the next time an email is entered. Because of this, you can allow people to fill out a form, have their email stored in a text file, and come view it whenever you please. The addresses will be broken up so that one address is on each line of the file.

But what about the confirmation email we promised the user in the above print statement? Have no fear, here’s the code:

$from = "your@email.com";
open (MAIL, "|/usr/sbin/sendmail -t") || &ErrorMessage;
print MAIL "To: $email nFrom: $fromn";
print MAIL "Subject: Confirmation Emailn";
print MAIL "Thank you for signing up. Your email address ($email) has been successfully ";
print MAIL "stored. Have a nice day.n";
close (MAIL);
sub ErrorMessage {
print "<P>The server has a problem. Aborting script. n";
exit;
}

The first line gives the $from variable a value – change the “you@email.com” text to reflect your address, but make sure to keep the backslach in front of the “@” symbol. This is necessary to avoid a parse error.

The second line specifies the path to “sendmail” on your server, and if it is incorrect or not found for some reason, it displays the error message found on under the heading “sub ErrorMessage.”

Lines 3, 4, and 5 print text into the email…it prints a little header showing who the email was sent TO ($email, the email the user entered into the form originally), and the address of the person sending the email ($from). Line 6 closes the email, and the rest is the aforementioned error message.

Here is the entire email.cgi script:

#!/usr/local/bin/perl

require “subparseform.lib”;
&Parse_Form;

$email = $formdata{’email’};

open (EMAILS, “>>emails.txt”);
flock(EMAILS, 2);
print EMAILS “$emailn”;
flock(EMAILS, 8);
close (EMAILS);

print “Content-type: text/htmlnn”;
print “Your email address ($email) has been successfully entered. “;
print “Thank you. You will receive a confirmation email shortly.”;

$from = “your@email.com”;
open (MAIL, “|/usr/sbin/sendmail -t”) || &ErrorMessage;
print MAIL “To: $email nFrom: $fromn”;
print MAIL “Confirmation Emailnn”;
print MAIL “Thank you for signing up. Your email address ($email) has been successfully “;
print MAIL “stored. Have a nice day.n”;
close (MAIL);
sub ErrorMessage {
print “<P>The server has a problem. Aborting script. n”;
exit;
}

4) Wrap-Up

Congratulations – assuming I didn’t lose you back somewhere back in Part one, you now know Perl’s basic syntax, how to print text, handle user-submitted information via an HTML form, send email with Perl, display different messages depending on the information submitted, and store user variables in a text file for your viewing convenience.

Hopefully you will now look at Perl and other programming languages with confidence rather than fear. Feel free to use and modify the code provided here almost as if it were your own.

Good luck, and happy coding!

Chris BowyerChris Bowyer
View Author

Chris is a regular on the SitePoint Forums and goes by the username "TWTCommish". He also runs the My Conding, Domain Mailings, The Stands and Movie Forums sites.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week