next up previous
Next: Writing, Creating and Running Up: Beginning CGI Programming in Previous: CGI Script Output

A First Perl CGI Script

Let us now look at how we write our first perl program that will be used as a CGI script.

We will learn three main things in here:

Format of a Perl program

Every Perl program MUST obey the following format:

Strictly speaking the first line is only required for running Perl programs on UNIX machines. Since that is the intended destination of most of our Perl scripts. It is a good idea to make this the first line of every perl program. What is the purpose of this first line?

The first line declaration has two purposes:

The first line is actually a comment (albeit a very special type of comment) Comments in Perl

It is good practice to comment all your programs (whatever the language (HTML, Perl, Pascal C) -- Comments serve you well.

In Perl comments are easy:

So a simple comment in Perl might be:

# hello.cgi - My first CGI program

Output from Perl

To output from a Perl script you use the print statement:

For Example, The first line of our CGI script must be `` Content-Type: text/html'' and the print statement must have 2 \n characters:

print "Content-Type: text/html\n\n";
Finally -- Our complete script

Recall that our Perl CGI script must output the header and HTML code and must begin with a special first line.

Our complete first program (with nice comments) is a follows:

#!/usr/local/bin/perl
# hello.cgi - My first CGI program

print "Content-Type: text/html\n\n";
# Note there is a newline between 
# this header and Data

# Simple HTML code follows

print "<html> <head>\n";
print "<title>Hello, world!</title>";
print "</head>\n";
print "<body>\n";
print "<h1>Hello, world!</h1>\n";
print "</body> </html>\n";


next up previous
Next: Writing, Creating and Running Up: Beginning CGI Programming in Previous: CGI Script Output
Dave Marshall
9/28/2001