3. Hello, World, from CGI

The next step is to modify your Hello, World program so that it can be run from a Web browser, as opposed to running it directly from the Perl interpreter, e.g., through the UNIX shell.

Recall two things from the discussion of CGI. First, output is sent from the program to the server via STDOUT; consequently, normal Perl print statements can be used to create the data that will be sent by the WWW server back to the user's WWW browser. Second, the data from the CGI program must begin with several header lines followed by a blank line. Those header lines include the Status code and the Content-type

The Status line includes two fields: a numeric return code and an explanation. We'll return values of "200" and "ok", on a line by themselves.

The Content-type describes the type of data that will be sent, expressed as a MIME type/subtype form. Since our data is text and will not be formatted in HTML, we'll use text/plain.

Finally, we'll put out a blank line to separate the header lines from the data produced by the program.

Hello, World, from CGI program


print "200 OK\n";
print "Content-type: text/plain\n";
print "\n";

print "Hello, World, from CGI\n";
I suggest you begin with your Hello, World program and modify it. Then test it as a conventional Perl program. After you see that it produces the output you want, copy it into your CGI directory.

Run the program. To do this, you must provide a Web browser with a URL to your program. It will look approximately like this, depending on how your local directory structure is setup:


If yours doesn't work for some reason, you can execute the program, above: Hello, World, from CGI.