» Perl CGI » Writing the First Perl CGI program
Writing the First Perl CGI program
Before continuing, let's write our first CGI program. Open up your Perl IDE and create a new file in the cgi-bin directory called hello.pl. Copy the following Perl code into that file:
-
#!/usr/bin/perl
-
-
print "Content-type: text/html\r\n\r\n";
-
print "<HTML>\n";
-
print "<HEAD><TITLE>Hello World!</TITLE></HEAD>\n";
-
print "<BODY>\n";
-
print "<H2>Hello World!</H2>\n";
-
print "</BODY>\n";
-
print "</HTML>\n";
-
-
exit (0);
The first line is known as the shebang, and informs the operating system of the program that can understand this code (perl, in this case). If your version of Perl is installed at another location, you will want to change this line to correspond (eg, under Windows it is common to put #!perl.exe on the first line). The next block of lines simply print out statements, and the last line exits the Perl interpreter cleanly.
You should try to run the program outside of the webserver first, to be certain that it works properly:
perl -w hello.pl
It should return everything that is printed out in the program. The 'w' flag above tells Perl to perform thorough checks, and to stop if it finds any errors or warnings. Next, we want to make sure the program runs by itself, without having to specify the Perl interpreter explicitly:
Windows
Type hello.pl and see if you get the expected result. Windows uses the filename to determine program association, in this case ActivePerl has registered the ".pl" extension to run the perl interpreter.
UNIX
Make the program readable and executable by everyone:
chmod a+rx ./hello.pl
Test it out:
./hello.pl
Now we are ready to run it through the webserver, so load up your favorite browser and test it out:
http://yourservername/cgi-bin/hello.pl
The result should look like this:

If you don't see what you expect, double-check the syntax of your code, and run through the test from the command line again. Check your error_log and access_log for any possible problems.
Congratulations! You've written your first CGI program.