19.3. Simplest CGI Program

Here's the source code for your first CGI program; it's so simple, it doesn't even need to use the CGI.pm module:

#!/usr/bin/perl -w
# howdy--the easiest of CGI programs
print <<END_of_Multiline_Text;
Content-type: text/html
 
<HTML>
    <HEAD>
    <TITLE>Hello World</TITLE>
    </HEAD>
    <BODY>
    <H1>Greetings, Terrans!</H1>
    </BODY>
</HTML>
 
END_of_Multiline_Text

Every time this program is called, it displays exactly the same thing. That's not particularly interesting, of course, but we'll spice it up later.

This little program contains just one statement: a call to the print function. That somewhat funny looking argument is a here document . It starts with two less-than signs and a word that we'll call the end token. Although this may look like I/O redirection to a shell programmer, it's really just a convenient way to quote a multiline string. The string begins on the next line and continues up to a line containing the end token, which must stand by itself at the start of the line. Here documents are especially handy for generating HTML.

The first part in that long string is arguably the most important: the Content-Type line identifies the type of output you're generating. It's immediately followed by a blank line, which must not contain any spaces or tabs. Most beginners' first CGI programs fail because they forget that blank line, which separates the header (somewhat like a mail header) from an optional body following it.[4] After the blank line comes the HTML, ...

Get Learning Perl, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.