1. Computing

'Hello World' using CGI.pm

How to Create a Simple Perl CGI using CGI.pm

From , former About.com Guide

We've already seen how to make a simple, raw CGI program using nothing but Plain ol' Perl to print our HTML, now it's time to discover an easier way to create CGI programs with Lincoln Stein's CGI.pm (Perl Module). CGI.pm typically comes with the standard installation of Perl, so there's usually nothing to do but include and use it. On the off-chance that you have an install of Perl without CGI.pm, or with an outdated version, it's freely available from CPAN.

There are several wonderful reasons to use CGI.pm over raw Perl and HTML, not the least of which is the nightmare a sprawling application would be with page after page of embedded HTML. It also correctly processes GET and POST variables so that you can access them quickly and easily, and performs a huge host of other CGI related tasks. Let's look at the full text of our CGI.pm 'Hello World' program and then dissect it line by line.

 #!/usr/bin/perl
 
 use CGI qw/:standard/;
 print header,
 start_html('Hello World'),
 h1('CGI.pm is simple.'),
 end_html; 
You'll undoubtedly notice is that the CGI.pm version of 'Hello World' is not only shorter, it's much easier to read. Using the built in functions, we can have CGI.pm worry about formatting and printing the HTML while we concentrate on programming. Obviously, the first thing you'll need to do is include the CGI.pm:
 use CGI qw/:standard/; 
The qw/:standard/ is to include only the standard portion of the module, which saves on memory if you don't need all of the CGI.pm's functionality in any particular script. Next we start a multi-line print statement, using commas and whitespace to break it up for an easier read. This particular script only uses four of CGI.pm's functions.
 print header, 
header() prints the Content-type headers, necessary to inform the web browser exactly what is coming at them. This is the CGI.pm version of printing your own raw header:
 print "Content-type: text/html\n\n"; 
Next we print the start of the HTML document, passing the function 'Hello World' as the title. This function prints the HTML <head> area.
 start_html('Hello World'), 
Then we'll print the words inside an <h1> tag:
 h1('CGI.pm is simple.'), 
And finally, close out the HTML body and document tags:
 end_html; 
That's all there is to it! Want more? Stay tuned, an extensive course on CGI.pm is coming soon.

©2013 About.com. All rights reserved.