Hello World

Enough background, lets get to the code. The classic "Hello World" program is a good place to start. We'll start with a static HTML document, and then show a CGI program that produces the same thing:

Static HTML
<html><body>
<p>Hello World</p>
</body></html>
CGI Code
#!/usr/bin/perl

#
# Tell the browser what type of file this is.   
# Note that the double newline is important.  That tells
# the web browser when page content begins.

print ("Content-Type: text/html\n\n");

# 
# print the HTML

print ("<html><body>
<p>Hello World</p>
</body></html>\n")

As you can see, the process of producing an HTML page in CGI is not much different than producing a hand coded static HTML page. The only extra piece of output is the "Content-Type" line. This line is read by the browser so that it knows what type of output to expect. In our example, it is HTML. However, it could have been any number of different file types such as a plain text file, a JPG graphic file, or a MS Word document.

If the document had been a plain text file, the print statements would have looked like this:

print ("Content-Type: text/plain\n\n");
print ("Hello World\n");

Next Previous Examples

Copyright 2001 - Andy Welter