Web Development with Perl – CGI – Hello World Example

Next couple lines describes simplest process of getting started with Perl and CGI on Linux system in particular Debian Linux. Although the following steps are performed on a Debian Linux system they should be valid for all other distributions expect the step of Apache web server installation. First we need to install Apache Web server:

# apt-get install apache2

for RPM based distribution this step could involve yum

# yum install apache2

If you did not get any major errors the apache2 web server should be up and running at this point. Therefore we can navigate to /usr/lib/cgi-bin directory

# cd /usr/lib/cgi-bin

and create a following function based CGI program named hello.cgi:

 
#!/usr/bin/perl -T 
use strict; 
use CGI ':standard'; 
print header; 
print start_html('Hello World'); 
print h1('Hello World'); 
print end_html(); 
exit; 

Here is an Object-Oriented alternative of the above program:

 
#!/usr/bin/perl -T 
use strict; 
use CGI; 
my $cgi = new CGI; 
print $cgi->header; 
print $cgi->start_html('Hello World'); 
print $cgi->h1('Hello World'); 
print $cgi->end_html(); 
exit; 

At this stage we need to make our new CGI program executable:

# chmod 755 /usr/lib/cgi-bin/hello.cgi

All is now ready to launch our first CGI based web page by navigating our browser to and IP address of the apache server. In my case I’m running Apache locally so I use a localhost:

http://localhost/cgi-bin/hello.cgi