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.
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:
#!/usr/bin/perl use CGI qw/:standard/; print header, start_html('Hello World'), h1('CGI.pm is simple.'), end_html;
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.
use CGI qw/:standard/;
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:
Next we print the start of the HTML document, passing the function 'Hello World' as the title. This function prints the HTML <head> area.
print "Content-type: text/html\n\n";
Then we'll print the words inside an <h1> tag:
And finally, close out the HTML body and document tags:
h1('CGI.pm is simple.'),
That's all there is to it! Want more? Stay tuned, an extensive course on CGI.pm is coming soon.