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.
#!/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;
The key line is the first print statement:
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.
print "Content-type: text/html\n\n";
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. In the next example, let's take part of our time and date script and put it in our web page.
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.
#!/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;