3. Using advanced functions of the CGI Perl Module

The CGI Perl module (CGI.pm) can do much more than simply extract parameters. It contains many functions to simplify the whole process of creating HTML documents and forms.
A list of the common set of functions is available.

With the HTML and FORM shortcuts built in to the CGI module, you can save a lot of typing and avoid common HTML errors. Even producing a simple web page can be reduced dramatically.


#!/usr/local/bin/perl -w

print <<END_of_HTML;
Content-type: text/html

<HTML>
<HEAD>
<TITLE> Hello</TITLE>
</HEAD>

<BODY>
<H1> Hello World</H1>
<P>
Hello everybody.
</P>
</BODY>

</HTML>
END_of_HTML


...can be shortened to

#!/usr/local/bin/perl -w
use CGI qw(:standard);

print header, start_html("Hello"), h1("Hello World"), p("Hello everybody."), end_html;

Built-in HTML elements

Some of the HTML shortcuts available in the CGI perl module are given in the table below. There are many other shortcuts available - see the Perl5 CGI Library documentation for more details.

CGI.pm Shortcut HTML equivalent
print header;

Content-type: text/html

print start_html ("My Home Page");

<HTML>
<HEAD>
<TITLE> My Home Page </TITLE>
</HEAD>
<BODY>

print start_html (
-title=>'My Home Page',
-author=>'mikey@mikey.org',
-meta=>{'keywords'=>'jokes,
chat, fun','description'=>
'Mikey's home page of fun'},
-BGCOLOR=>'white');
<HTML>
<HEAD>
<TITLE> My Home Page </TITLE>
<META NAME="keywords"
CONTENT="jokes, chat, fun">
<META NAME="description"
CONTENT="Mikey's home page of fun">
</HEAD>
<BODY BGCOLOR="white">

print p, br, hr;

<P> <BR> <HR>
print h1("hello"); <H1>hello</H1>
print a( {-href=>"page2.html"},
"Jump to page two");
<A HREF="page2.html">Jump to page two</A>
print ul (
li(a({href=>"apple.html"},"apples")),
li(a({href=>"orange.html"},"orange")),
li(a({href=>"pear.html"},"pear"))
);
<UL>
<LI><A HREF=<"apple.html">apple</A></LI>
<LI><A HREF=<"orange.html">orange</A></LI>
<LI><A HREF=<"pear.html">pear</A></LI>
</UL>

Basic Form using CGI.pm shortcuts

Using the full range of functions allows you to create a cgi program that produces the page containing the form, as well as the results page.

This example is similar to the earlier form, in that it asks for a name and returns a page containing that name.

View the Basic CGI Program

Run the Basic CGI Program

Things to note
To use the standard HTML shortcuts as well as CGI parameter handling, insert the line:

use CGI qw(:standard);

Advanced form that remembers state

View the Basic CGI Program

Run the Basic CGI Program

 

Ok, ready for the next step...
Back - Next