Hello World

Overview
Objectives
Installing Apache
Installing Perl
Lesson 1
Hello World
Anatomy of a CGI Program
Hello World with CGI.pm
Lesson 2
HTML Forms and DOM
POST and GET
A Form Example
Lesson 3
Cookie Tutorial
Database Tutorial

Software Links
FAQ / Terminology
Contact the Author

 

Before continuing, let's write our first CGI program. Open up your favorite editor (I like XEmacs myself) and create a new file in the cgi-bin directory called hello.pl. Copy the following Perl code into that file:

#!/usr/bin/perl

print "Content-type: text/html\r\n\r\n";
print "<HTML>\n";
print "<HEAD><TITLE>Hello World!</TITLE></HEAD>\n";
print "<BODY>\n";
print "<H2>Hello World!</H2>\n";
print "</BODY>\n";
print "</HTML>\n";

exit (0);

The first line is known as the shebang, and informs the operating system of the program that can understand this code (perl, in this case). If your version of Perl is installed at another location, you will want to change this line to correspond (eg, under Windows it is common to put #!perl.exe on the first line). The next block of lines simply print out statements, and the last line exits the Perl interpreter cleanly.

You should try to run the program outside of the webserver first, to be certain that it works properly:

perl -w hello.pl

It should return everything that is printed out in the program. The 'w' flag above tells Perl to perform thorough checks, and to stop if it finds any errors or warnings. Next, we want to make sure the program runs by itself, without having to specify the Perl interpreter explicitly:

Windows

Type hello.pl and see if you get the expected result. Windows uses the filename to determine program association, in this case ActivePerl has registered the ".pl" extension to run the perl interpreter.

UNIX

Make the program readable and executable by everyone:

chmod a+rx ./hello.pl

Test it out:

./hello.pl

Now we are ready to run it through the webserver, so load up your favorite browser and test it out:

http://yourservername/cgi-bin/hello.pl

The result should look like this:

http://inconnu.islug.org/cgi-bin/perl_tut/hello.pl

If you don't see what you expect, double-check the syntax of your code, and run through the test from the command line again. Check your error_log and access_log for any possible problems.

Congratulations! You've written your first CGI program.


All pages written by Craig Kelley unless otherwise specified. Please use the Contact link from the menu to submit changes or suggestions. Permission is given to use this tutorial in any way you wish including re-publishing or "mirroring". The most up-to-date version of this document currently resides at http://inconnu.islug.org/~ink/perl_cgi.

This page updated: May 6, 2002 22:21