Example 2 - CGI scripting

Perl has proven to be arguably the best tool for the rapid development of Common Gateway Interfaces (CGI) to the World-Wide Web.

Here are three examples of Perl CGI scripts:

  1. CGI test page
  2. A web page hit counter
  3. A simple visitors form

CGI test page

This test script uses the cgi-lib library to display all of the form variables and environment variables. This is useful or debugging form pages.

The use of the cgi-lib library simplifies the CGI script down to a handful of lines.

A web page hit counter

For some bizarre reason, everyone has to advertise how many people have wandered through their web site. Here is my contribution to the craze.

In about a dozen lines of Perl code we have implemented a simple web page counter that uses a central database to keep track of all pages on the server, can be used by anyone who has access to server-side includes, and took less than ten minutes to write and test.

A simple visitors form

A more practical use of CGI interfacing is using Perl as a back-end for a visitor's form.

The Perl code for this has been deliberately stripped down to illustrate the fundamental points of the script - a more elaborate script could also handle:


  1. Use the die command as much as you can - the error messages will be logged in the server's error log which makes the tedious CGI debugging process a lot easier
  2. The -w flag will flag down subtle errors; saving you from lots of debugging headaches
  3. Take security very seriously - do not directly evaluate any user input!
  4. Use libraries and modules as much as possible

For more information

The NCSA CGI Overview CGI.pm - a Perl5 CGI library

The best newsgroup is probably comp.infosystems.www.authoring.cgi, if you can cope with the varying signal:noise ratio.

Next - Perl & Linux Updated: 5 December, 1995