1. Home
  2. Computing & Technology
  3. Perl

Working with CGI.pm In-Depth - Creating an HTML Document

From , former About.com Guide

1 of 5

Overview

Perl's CGI module, CGI.pm, is a quick and easy way to create CGI applications with embedded HTML. It saves you the hassle of editing and working with actual HTML in your perl programs, or dealing with the overhead of a templating system. We've already had an in depth look at creating the document headers in our first look at CGI.pm - this time we're going to explore how we create the actual start of our HTML document.

This time we're going to take a close look at the start_html, which is used to generate the start of our actual HTML document. Once we've sent our document headers and told the client to expect HTML, we need to send it the proper data. Again, for these examples, we will just be printing HTML to the command line of our system, so there's no need for an actual web browser.

To start with, lets look at the default output of CGI.pm's start_html function:

#!/usr/bin/perl -w

use strict;
use CGI;
my $cgi = new CGI;

print $cgi->start_html;
Running this program will generate the following output:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US"><head><title>Untitled Document</title>
</head><body>
With the default value, it's sending a valid XHTML 1.0 Transitional header, but there's one glaring problem. If you scan down, you'll see that the page's title tag says Untitled Document - and we don't want to be outputting untitled documents! This brings us to our first attribute for the start_html function, the one that gives us a title.
Explore Perl
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Perl
  4. CGI & Web
  5. Working with CGI.pm In-Depth - How to create an HTML document header with CGI.pm

©2009 About.com, a part of The New York Times Company.

All rights reserved.