So far, this has been pretty thin gruel. To do more complicated things in an easier fashion, we introduce the Perl/CGI programmer's friend: CGI.pm.
CGI.pm is a Perl module written by Lincoln Stein. Our discussion of CGI.pm is just an introduction. Much more documentation is available. We recommend that you check out Lincoln Stein's Official Guide to Programming with CGI.pm [Stein 98]. You can also check out the CGI.pm documentation with perldoc CGI .
To use CGI.pm, tell Perl that you want to use it with the use pragma:
After Perl executes this statement, your program has access to all the methods that CGI.pm provides. The module can be further refined by specifying a more convenient programming style, called the standard style:
use CGI :standard;
Here's an example of some simple HTML that creates Figure 7.7:
Figure 7.7. A simple page with CGI.pm
#!/usr/bin/perl # simple.cgi use CGI :standard; print header(), start_html(-title => A Simple Page, -bgcolor => #ffffff, -text => #520063), h1(Hello, world! again), hr(), Time to go now..., end_html();
The fourth line indicates that we want to use the CGI.pm module, passing the string :standard into the use pragma. This ensures that we will use only functions that are appropriate for the widest range of browsers, up to HTML version 3. To use all the HTML there is, we could use CGI :all ; . These are the two most widely used options.
The use of :standard also enables us to call CGI.pm methods such as hr() directly without an object. If we did not use :standard mode, we would have to create a CGI object and execute the methods with it, as in this code:
$q = new CGI; print $q->header(), . . $q->hr(), . .
As you can see, using :standard mode is much nicer ”it looks cleaner and we avoid the difficult-to-type $q-> . Also, using :standard ensures you of the widest possible audience because the HTML generated will support most major browsers.
The rest of the program is all part of the same print() function call. We could have printed each piece separately, but the convention is to combine the multiple print s into a single print() function.
These are the other methods used in this program.
This program can be run from the command line to see the output (enter ctrl-D after the offline mode prompt):
$ ./simple.cgi (offline mode: enter name=value pairs on standard input) ^D Content-Type: text/html <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <HTML><HEAD><TITLE>A Simple Page</TITLE> </HEAD><BODY TEXT="#520063" BGCOLOR="#ffffff"><H1>Hello, world! again</H1> <HR>Time to go now...</BODY></HTML>