next up previous contents
Next: Fill-out Forms Up: Perl on the Web Previous: A Simple CGI program   Contents

The CGI module

There are several different ways to access the CGI module; we're going to consider only the object-oriented interface, since it's similar to many other perl modules. There is no difference in functionality between the different ways of accessing the module; the method you choose is a matter of personal taste. To learn more about the different methods, view the online documentation available through the command ``perldoc CGI''.

Like the IO module (Section [*]), the first step in using the CGI module is to inform perl you need it through the use directive. Next, a CGI object is created with a call to the new method provided by CGI. Most of the methods provided by CGI simply produce a piece of HTML code -- you use the print function to print them, and a user accessing your program will see the results of the generated HTML in their browser. Here's the previous perl program, with parts of the code replaced with some of the CGI methods:

use CGI;
$q = new CGI();
print $q->header(),$q->start_html("The Time"),$q->h1("This is the time!");
printf qq{The time is now %s<br>Thanks for visiting},scalar localtime;
print $q->end_html();
Most of the details of producing usable HTML have been eliminated. The header (defaulting to Content-type: text/html) is produced by the header method, the start_html method accepts a string to be used as a title for the document (displayed on the browsers title bar, not in the document itself), and the explicit tagging of the title with the H1 tag has been replaced by a call to the h1 method. Most of the HTML tags have corresponding methods in the CGI module; when they are passed an argument, they return the argument surrounded by the appropriate start and end tags. (See Section [*] for details on more advanced ways to use these methods.) Finally the end_html method closes the BODY and HTML tags, an important detail which, when overlooked, causes some browsers to display a blank page.


next up previous contents
Next: Fill-out Forms Up: Perl on the Web Previous: A Simple CGI program   Contents
Phil Spector 2002-10-18