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 end_html
method closes the BODY
and HTML
tags, an important
detail which, when overlooked, causes some browsers to display a blank page.