Active Web Hosting Logo


Using Perl

Perl is a scripting language which allows you to add special features to your web page. With Perl, you can allow your visitors to send you email using a feedback form, select options on your site and send you the results, create interactive web sites, and much more. There are many perl script packages out there, including counters, blog systems, and email forms.

Writing a basic perl script is not that hard. Perl is used by advanced programmers as well. You do want to be sure to learn how to Create A Web Page before you learn Perl. In addition, learning Perl does take a little time and patience when you start to make longer and more complicated scripts. You will want to work slowly and try to understand each section and how it works, before you move on. Perl requires that you place the files on your CGI Server. Click Here to learn more about the CGI Server. Once you have your CGI account set up, you will be ready to start writing perl scripts of your own!

Creating and Running Scripts

To write a perl script, you will need a plain text editor. Please see Text Editors You Can Use To Create CGI Scripts for recommendations on what text editor is best to use to write your scripts. Once you have your text editor ready. Run it and type in the sample code in this tutorial. Save each sample to a separate text file as recommended. Usually, perl scripts are saved with the extension .cgi but sometimes also with the .pl extension.

Once you upload your script to your CGI server, you need to set the permission of your script to executable. This means, in your FTP Program, set the file permission to 755. We have a list of tutorials on how to use various FTP programs here.

Now you can run your script in your web browser by typing the direct URL to the script filename. For example, http://cgi.yourdomain.com/yourdirectory/hello.pl where yourdomain.com represents your actual domain name, yourdirectory represents the directory you saved your script in (it's recommended you create a directory on your CGI server to put your scripts in), and hello.pl would be replaced with the actual filename of the script you uploaded.

Your First Perl Script

Now we'll start our very first perl script. We will want to name this one hello.pl when we save the file. Type in the code below into your text editor and we'll take a look at it. Do not type in the line numbers.

1 #!/usr/bin/perl
2 #
3 # Hello World
4
5 print "Content-Type: text/plain", "\n\n";
6 print "Hello World.";
7
8 # End Script


Now let's look at the script above. Line 1 is probably the most important. Virtually all executable perl scripts require this to run. This gives the exact location of the perl parser which is required to run the script.

You'll notice that lines 2, 8 and 8 start with a # as does line 1. Lines 2, 3 and 8 are called comment lines and are ignored by the perl interpreter. You can use comment lines to make notes and remind yourself what the script does, or what variables are for, functions, etc. Every line you want to make as a note (ie. comment) should start with a hash (#). Now there is a difference between these and the # in line 1. Line 1 uses a #! (shebang) and this is a special notation just for noting where the perl interpreter is located. It should not appear anywhere else in your perl script.

Now we get to the part that makes your script work. Looking at line 5, we see a print statement. This says to print something in the web browser or screen. In this case, since we are sending text to the web browser, we need to tell the web browser what type of information we are sending it. Thus the rather cryptic Content-Type: text/plain. The \n means to skip one line, like hitting the Enter key in your text editor.

Line 6 is what we want the script to do; Print "Hello World." in the web browser.

Note that each line where we give an instruction (ie. a statement) is ended by a semi-colon. This is necessary in a lot of perl script statements.

Keep in mind that we are essentially writing an HTML page here. If you view this in your web browser by going to http://cgi.yourdomain.com/hello.cgi, it should show the words: Hello World. If you view the source of the page in your web browser, you should see the same thing. What happened to the text we printed in line 5? Remember, this only is there to tell the web browser what type of information to disply.

Creating The Web Form

Now that you got your feet wet and learned how to create and run a perl script, we'll take a look at how to make something useful. We will look at how to use perl to get data from a form and display this information in the web browser. This can become quite useful especially in creating interactive web sites.

We will start first with building a web form. Copy and paste the code from the text box below into a text file. Change the following line so that yourdomain.com is replaced by your actual domain name:

<form action="http://cgi.yourdomain.com/test/parseform.cgi" method="post">

When done, save it as formtest.html. Upload this file to your web server, not your CGI server.

formtest.html

Let's take a look at some of the code while it's in your text editor. You'll see many different types of form input which you can access in your script. Let's look at them one by one:

<form action="http://cgi.yourdomain.com/test/parseform.cgi" method="post">

This starts the form area. Note the http:// portion. This is the full URL to your script. The method usually should be post. This way the information on the form will be passed without showing up in the address bar of the web browser.

1. What color is a stop sign? <input type="text" size="20" name="stop_color"><br>
<br>

Note the name="stop_color" in the code above. This is the name of the parameter which we will use to store whatever the visitor typed into the input box. Perl uses the param() function to store each of the different parameters that you have set up in your form. stop_color is one of the parameters. You can name parameters anything you like as long as they contain numbers or letters (always starting with a letter) and you may use an underscore if you wish. You can not use other symbols, characters, or even spaces or punctuation.

2. Which light means you can go? <select name="light_color">
<br>
<option value="red">Red</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
</select><br>
<br>

Now we try a drop down box. This is done differently. Instead of putting our parameter in the name= field, we use the value= field to store our parameter name. The text between the option tags is what will show up in the drop down box. It's always best to use all lower-case letters as it makes it easier to work with in the script. Also it's best to make the parameter name something which will remind you of what the text said. Here we made them the same. Also, what is between the option tags is also what is stored inside the parameter. So if the user chose green, then the 'green' parameter would store the word 'green'.

3. True or False: Elephants are purple. <input type="radio" name="elephant" value="true"> True <input type="radio" name="elephant" value="false"> False<br>
<br>

The top part is long and should be all on one line. The <br> should be on it's own line separate. This example shows you a radio button set. Note that the name= for both is elephant. Elephant is the name of our parameter. However, there are two choices for this parameter; true or false. The choices are stored in the value= field. So if a visitor chose true, then the elephant parameter would contain the word true.

4. Check all that apply:
<br><br>
<input type="checkbox" name="choices" value="december">December is the 12th Month of the Year.<br>
<input type="checkbox" name="choices" value="sun">The Sun always shines everywhere.<br>
<input type="checkbox" name="choices" value="purple_houses">There is no such thing as a purple house.<br>
<input type="checkbox" name="choices" value="people">The world has many different people in it.
<br><br>

Now we have another form type called a checkbox. This set of check boxes uses a parameter called choices, which appears in the name= field of all the choices. This is so we can group all these into one area which will make it very easy to work with in the script. The value= contains what will be stored in the choices paramter. The text after the input tag is what is displayed in the web browser. Since this text is quite long and contains spaces, we have used one or two words in the value= to remind us what those sentenses contained. So, if a visitor clicks on the box next to "December is the 12th Month of the Year." then the parameter choices will contain the word "december". Then we just will need to have our script see if the word "december" is in the parameter "choices" and we will know that the user had chosen that particular sentence.

<input type="submit" value="Submit">  <input type="reset" value="Reset">

This last line sets up the submit and reset button. The submit button will submit the form, and pass all the information and parameter names to the script. The Reset button will clear all the form fields and not pass anything to the script, but lets the user start over.

Now we are ready to write the script portion.

Creating The Script

Copy and paste the following into a new document in your text editor. Save the file as parseform.cgi. Log into your CGI server and create a new directory called test. Move to that directory and upload your parseform.cgi file there. Be sure to change the file permission of that file to 755 so it can execute as a script.

parseform.cgi

Now we can look at this script one section at a time.

#!/usr/bin/perl
#
# Form Demo
use CGI qw/:standard/; # Lets us the CGI features.


Here we see our normal start of the script. However, we also added another line which tells us to use the standard CGI features, including the ability to read and parse web forms.

# Set Up Variables, One for each item in the forms.
$visitor_name = param("visitor_name");
$stop_color = param("stop_color");
$light_color = param("light_color");
$elephant = param("elephant");
@choices = param("choices");


Now we set up what are called variables. Variables store values. Here we are storing the values that were stored in the parameters which we named in the web form above. The param() function grabs the value stored in the parameter name which is enclosed within quotation marks. For example, the variable $visitor_name will store whatever the visitor typed into the text box in the web form, which we stored into the parameter named visitor_name (ie. name="visitor_name" in our HTML code for formtest.html). You can name variables anything you want, as long as you follow the same rules you do when naming parameters in the web forms. We keep things simple by naming the variables the same as the parameters.

Look at the last variable. @choices is actually an array. Arrays store a group of values. @choices stores all the different values that were added to the choices parameter. This means that every time a visitor checks a check box, the word inside the value= in that part of the code was stored in the choices parameter. Now, these very same words will be stored in the @choices array so we can work with them.

# Start creating the HTML page
print "Content-Type: text/html", "\n\n";
print "<html><head>\n";
print "<title>Results Of Your Test</title>\n";
print "</head><body bgcolor='white' text='blue'>\n";
print "<center><h1>Results Of Your Test</h1></center>";


Remember, we are going to create an HTML page to display the results. This is basically a start of the HTML code that will be sent to the browser. You probably by now can recognize some of the code here, though it's inside print statements.

# Greet the visitor;
print "Hello, $visitor_name! Let's take a look at the results:<br><br>";


Here we greet the visitor. Notice we put the variable $visitor_name right into the print statement. Anytime a variable name appears inside a print statement that is enclosed in quotation marks, the contents of the variable will be displayed in it's place. Notice also we can use HTML tags in our print statements as well.

# Analyze 1. What color is a stop sign?
print "<b>1. What color is a stop sign?</b><br><br>";
if (($stop_color eq "red") || ($stop_color eq "Red")) {
  print "You were correct! Stop Signs are red.";
} else {
  print "Sorry, Stop Signs are not '$stop_color'. They are red.";
}
print "<br><br>";


Now we'll take a look at what the visitor typed in for the first question. We stored the input in the parameter stop_color in our web form, which ended up in the variable $stop_color. We now test to see if the word "red" or "Red" was typed. You'll notice an if statement is shown, which tests anything within parenthesis (), and if true, executes anything within the brackets {}. You can also use an else after the if statement and it will execute anything in the brackets after the else if the test is not true. Here is a basic example:

if ( test ) {   # Do something here if true } else {   # Do something here if false }

Another shorter way to write an if statement is this:

( test ) ? # Do something here if true : # Do something here if false;

Note the ? and : symbols. Basically, you put the test first, then the question mark and then your statements separated by a colon. Note that you can not use this method if there will not be something to do if the statement is false.

Taking a look back at our 'if' statement, we also see the following test:

($stop_color eq "red") || ($stop_color eq "Red")

The eq means equals. The double pipes (||) means or. So, reading this, it would mean if the value of the variable $stop_color contains the word "red" or if the variable $stop_color contains the word "Red" (notice the difference in capitalization), then execute the next code (meaning to print the sentence "You were correct! Stop Signs are red.")

Also notice after each block of code, we also insert a print "<br><br>"; so that we skip a couple lines and can display our data neatly on the web page.

# Analyze 2. Which light means you can go?
print "<b>2. Which light means you can go?</b><br><br>";
if ($light_color eq "red") { print "Sorry, you should never go when the light is red!"; }
if ($light_color eq "yellow") { print "You should slow down and prepare to stop when the light is yellow."; }
if ($light_color eq "green") { print "You are correct!"; }
print "\nA green light means you can go.";


Here we will see what was chosen for the second question, which we gave choices using a drop-down list box. Notice we are testing for each value we used in the options tag in our form, and printing a repsonse depending on if the option was chosen. Again, we are going by what value was placed in the parameter from the web form. We got the parameter name from the select name="light_color" part of the web form. The values from the options tags were stored into that light_color parameter which we then stored into the $light_color variable at the beginning of our script. By now, it should be becoming easier to see how this works.

print "<b>3. True or False: Elephants are purple.</b><br><br>";
($elephant eq "true") ? print "Sorry, Elephants are never purple. They are gray." : print "You are right! Elephants are gray!";


The second line actually should go all on one line. You can see here we used a shortened version of the 'if/else' statement to test if the radio button 'true' was selected or if it was the 'false' radio button. If it was true, then the first print statement would be done, otherwise it would go and do the second print statement.

# Analyze"4. Check all that apply:
print "<b>4. Check all that apply:</b><br><br>";
for $i(@choices){
  if ($i eq "december"){ print "You are right. December is the 12th Month of the year.<br>"; }
  if ($i eq "sun"){ print "No, there are some times when the sun does not shine.<br>"; }
  if ($i eq "purple_houses"){ print "Sorry, some people do paint their houses purple!<br>"; }
  if ($i eq "people"){ print "You are correct! The world has many different people in it.<br>"; }
}


Note that above, each if statement is actually on one line of it's own in the original script code. Here you see we are testing our check box options. This time however, we do this using a for loop. Notice the for $i(@choices) portion of the code. The $i variable keeps track of the different values stored in the @choices array. Remember, these are the different choices which were put in the value= portion of the form checkboxes. You'll see that each of the tests we used above test for this very value, and print out a sentence depending on which values were chosen. If the value wasn't chosen, then that sentence is ignored and not printed. In the for loop, the items you want to do for each of the items is enclosed in brackets. So it will loop through all the choices and conduct each one of those tests each time it encounters a choice. Here's an example of how this would work. Suppose the choices turned out to be "sun" and "people". Since "december" and "purple_houses" weren't selected, then they would not appear in the list.

$i = "sun"
if $i equals "december" (it doesn't, so the rest is ignored).
if $i equals "sun", it does so we print the sentence
  "No, there are some times when the sun does not shine." in the web browser.
if $i equals "purple_houses" (it doesn't, so the rest is ignored).
if $i equals "people" (it doesn't, so the rest is ignored).
Do next one, i$ = "people", the only other choice stored.

The same tests are conducted all over again, this time the test is true for "people" so the corresponding sentence is printed. So there will be two sentences printed:

No, there are some times when the sun does not shine.
You are correct! The world has many different people in it.


Now you can see how the script works and how you can get input from various form elements into your script. You can use this to make all kinds of tests, and even score these tests, or create other types of interactive sites.

What To Do About The '500 Internal Server Error'

This is a general error that can mean almost anything. This is probably the most common type of error you get when creating your Perl scripts. If you encounter such an error, go back over your script code and make sure it is written correctly. Even some syntax errors can cause this error to appear in your browser. For more information on diagnosing this problem, please see Error 500: 'Internal Server Error' When Running CGI or Perl Scripts.

Security Issues

Please do keep in mind as you gain experience and make larger scripts, you will want to be sure that your scripts are secure. This means you must be sure people can not input data you do not expect your script to handle. For example, do not let them type in HTML or JavaScript code.

Learing More About Perl

This tutorial only covers the basics. This can get you started writing very simple scripts to parse your web site forms. However, there are many more things you can do with Perl other than what was presented here. For more information and a list of useful books and tutorials for you to study further, see our Perl section in More Information About CGI, Perl, and Other Scripting Languages.

 


Home - Support - Management - About Us
... Active Web Hosting, 213 N Stephanie St G318, Henderson, NV 89074 ...
Phone 702-449-2337