Hello World CGI

How to create a simple Perl CGI

Man working on computer
Luis Alvarez/E+/Getty Images

A CGI script can be as simple or complex as you need it to be. It could be in Perl, Java, Python or any programming language. At its core, a CGI application simply takes a request via HTTP (typically a web browser) and returns HTML. Let's look at a simple Perl Hello World CGI script and break it down into it's simplest forms.

'Hello World' CGI Perl Script

 #!/usr/bin/perl
 
 print "Content-type: text/html\n\n";
 print <<HTML;
 <html>
 <head>
 <title>A Simple Perl CGI</title>
 </head>
 <body>
 <h1>A Simple Perl CGI</h1>
 <p>Hello World</p>
 </body>
 HTML
 exit; 

If you run the program on the command line, you'll see that it does exactly what you'd expect. First, it prints the Content-type line, then it prints the raw HTML. In order to see it in action in a web browser, you'll need to copy or upload the script to your web server and make sure the permissions are set correctly (chmod 755 on *nix systems). Once you've set it correctly, you should be able to browse to it and see the page displayed live on your server.

The key line is the first print statement:

 print "Content-type: text/html\n\n"; 

This tells the browser that the document coming after the two newlines is going to be HTML. You must send a header so the browser knows what type of document is coming next, and you must include a blank line between the header and the actual document.

Once the header is sent, it's just a matter of sending the HTML document itself. In the above example, we're using a here-doc to simplify printing a large chunk of plain text.

Of course, this is really no different than having a plain HTML document sitting on your server. The real power of using a programming language like Perl to create your HTML comes when you add in some fancy Perl programming.

Adding on to the Basic Script

In the next example, let's take part of this time and date script and add it to your web page.

 #!/usr/bin/perl
 
 @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
 @weekDays = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
 ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
 $year = 1900 + $yearOffset;
 $theTime = "$weekDays[$dayOfWeek] $months[$month] $dayOfMonth, $year";
 
 print "Content-type: text/html\n\n";
 print <<HTML;
 <html>
 <head>
 <title>A Simple Perl CGI</title>
 </head>
 <body>
 <h1>A Simple Perl CGI</h1>
 <p>$theTime</p>
 </body>
 HTML
 exit; 

This new CGI script will insert the current date into the page each time the script is called. In other words, it becomes a dynamic document that changes as the date changes, rather than a static document.