Difference between revisions of "Perl CGI Hello World"

From The Uniform Server Wiki
Jump to navigation Jump to search
m (Reverted edits by Demver5 (Talk); changed back to last version by Ric)
Line 1: Line 1:
<span id="top"></span>
+
=[http://ojaperiwiva.co.cc This Page Is Currently Under Construction And Will Be Available Shortly, Please Visit Reserve Copy Page]=
{| cellpadding="2"
+
&lt;span id=&quot;top&quot;&gt;&lt;/span&gt;
 +
{| cellpadding=&quot;2&quot;
 
|__TOC__||'''Perl CGI - Hello World'''
 
|__TOC__||'''Perl CGI - Hello World'''
 
|}
 
|}
Line 12: Line 13:
 
{|
 
{|
 
|-
 
|-
!Shebang!!&nbsp;||Notes
+
!Shebang!!&amp;nbsp;||Notes
 
|-
 
|-
|valign="top"|
+
|valign=&quot;top&quot;|
<pre>#!/usr/bin/perl</pre>
+
&lt;pre&gt;#!/usr/bin/perl&lt;/pre&gt;
 
|
 
|
&nbsp;
+
&amp;nbsp;
 
|
 
|
It has the following format: Starts with a hash "'''<nowiki>#</nowiki>'''" followed by an exclamation mark "'''!'''" and then the complete path on your system to the '''Perl''' program itself.
+
It has the following format: Starts with a hash &quot;'''&lt;nowiki&gt;#&lt;/nowiki&gt;'''&quot; followed by an exclamation mark &quot;'''!'''&quot; and then the complete path on your system to the '''Perl''' program itself.
  
The shebang shown corresponds to Uniform Server running either in portable-mode (basic) or disk-root. The line informs Apache where to find the Perl program, "'''/'''" means start at the top level of a disk then follow the folder path '''usr''', '''bin''' and finally the name of the Perl program '''perl'''.exe note the file extension is assumed.
+
The shebang shown corresponds to Uniform Server running either in portable-mode (basic) or disk-root. The line informs Apache where to find the Perl program, &quot;'''/'''&quot; means start at the top level of a disk then follow the folder path '''usr''', '''bin''' and finally the name of the Perl program '''perl'''.exe note the file extension is assumed.
 
|-
 
|-
|valign="top"|
+
|valign=&quot;top&quot;|
<pre>#!c:/UniServer/usr/bin/perl</pre>
+
&lt;pre&gt;#!c:/UniServer/usr/bin/perl&lt;/pre&gt;
 
|
 
|
&nbsp;
+
&amp;nbsp;
 
|
 
|
 
When Uniform Server is installed as a service all Perl shebangs are changed to match the installation path. An example of this shebang is shown for a default installation of Mona installed as a service. Hence when writing new scripts remember to use the correct path for the shebang.  
 
When Uniform Server is installed as a service all Perl shebangs are changed to match the installation path. An example of this shebang is shown for a default installation of Mona installed as a service. Hence when writing new scripts remember to use the correct path for the shebang.  
Line 32: Line 33:
  
 
'''''Note 1'':''' The shebang can take parameters the most useful is '''-w''' it enables warnings remove it on finished scripts.
 
'''''Note 1'':''' The shebang can take parameters the most useful is '''-w''' it enables warnings remove it on finished scripts.
* <nowiki>#!/usr/bin/perl -w</nowiki>
+
* &lt;nowiki&gt;#!/usr/bin/perl -w&lt;/nowiki&gt;
* <nowiki>#!c:/UniServer/usr/bin/perl -w</nowiki>
+
* &lt;nowiki&gt;#!c:/UniServer/usr/bin/perl -w&lt;/nowiki&gt;
  
 
'''''Note 2'':''' Forward slashes are Unix paths if you wish you can use a back slash the path must be enclosed in quotes.
 
'''''Note 2'':''' Forward slashes are Unix paths if you wish you can use a back slash the path must be enclosed in quotes.
* <nowiki>#!"\usr\bin\perl"</nowiki>
+
* &lt;nowiki&gt;#!&quot;\usr\bin\perl&quot;&lt;/nowiki&gt;
* <nowiki>#!"c:\UniServer\usr\bin\perl"</nowiki>
+
* &lt;nowiki&gt;#!&quot;c:\UniServer\usr\bin\perl&quot;&lt;/nowiki&gt;
  
 
'''''Note 3'':''' For maximum computability always use '''forward slashes''' and run Uniform Server in portable or disk-root mode.  
 
'''''Note 3'':''' For maximum computability always use '''forward slashes''' and run Uniform Server in portable or disk-root mode.  
Line 45: Line 46:
 
The first thing a CGI script must perform is to output a header. This header is checked by Apache and then passed on to a users browser informing it what type of file to expect. In the hello world examples we are outputting an HTML file hence the header looks like this:
 
The first thing a CGI script must perform is to output a header. This header is checked by Apache and then passed on to a users browser informing it what type of file to expect. In the hello world examples we are outputting an HTML file hence the header looks like this:
 
{|
 
{|
|valign="top"|
+
|valign=&quot;top&quot;|
<pre>print "Content-type: text/html\n\n";</pre>
+
&lt;pre&gt;print &quot;Content-type: text/html\n\n&quot;;&lt;/pre&gt;
 
|
 
|
&nbsp;
+
&amp;nbsp;
 
|
 
|
Its important to output it exactly as shown. Must start with a capital "C" followed by lowercase characters. Of importance are the two newline characters (\n\n) at the end of the header. The header needs to be followed by a blank line hence the second newline character.
+
Its important to output it exactly as shown. Must start with a capital &quot;C&quot; followed by lowercase characters. Of importance are the two newline characters (\n\n) at the end of the header. The header needs to be followed by a blank line hence the second newline character.
 
|-
 
|-
|valign="top"|
+
|valign=&quot;top&quot;|
<pre>print "Content-type: text/html\r\n\r\n";</pre>
+
&lt;pre&gt;print &quot;Content-type: text/html\r\n\r\n&quot;;&lt;/pre&gt;
 
|
 
|
&nbsp;
+
&amp;nbsp;
|valign="top"|
+
|valign=&quot;top&quot;|
 
The above works fine on Windows.
 
The above works fine on Windows.
  
Line 69: Line 70:
 
|-
 
|-
 
|   
 
|   
<pre>
+
&lt;pre&gt;
 
#!/usr/bin/perl
 
#!/usr/bin/perl
  
 
# test_1.pl - First Perl Script!
 
# test_1.pl - First Perl Script!
print "Content-type: text/html\r\n\r\n";
+
print &quot;Content-type: text/html\r\n\r\n&quot;;
print "Hello World\n"; # Comment starts
+
print &quot;Hello World\n&quot;; # Comment starts
</pre>
+
&lt;/pre&gt;
 
|
 
|
&nbsp;
+
&amp;nbsp;
 
|
 
|
 
The first line is the shebang informing Apache where to find the Perl program.
 
The first line is the shebang informing Apache where to find the Perl program.
  
The second line starts with a hash "#" indicating the start of a comment, any character after this up to the end of a line are ignored. Although the shebang starts with a hash it is not a comment because it is combined with an exclamation mark the two together define a shebang. You can start a comment anywhere along a line, if a line is Perl code a comment must start after the line terminator character ";" semi-column.     
+
The second line starts with a hash &quot;#&quot; indicating the start of a comment, any character after this up to the end of a line are ignored. Although the shebang starts with a hash it is not a comment because it is combined with an exclamation mark the two together define a shebang. You can start a comment anywhere along a line, if a line is Perl code a comment must start after the line terminator character &quot;;&quot; semi-column.     
 
|}
 
|}
 
The third lines outputs (prints) the header.
 
The third lines outputs (prints) the header.
Line 91: Line 92:
 
* Copy this file to folder: '''UniServer\udrive\cgi-bin'''
 
* Copy this file to folder: '''UniServer\udrive\cgi-bin'''
 
* Start the servers.
 
* Start the servers.
* Type the following into a browser: '''<nowiki>http://localhost/cgi-bin/test_1.pl</nowiki>'''  
+
* Type the following into a browser: '''&lt;nowiki&gt;http://localhost/cgi-bin/test_1.pl&lt;/nowiki&gt;'''  
 
'''''[[#top | Top]]'''''
 
'''''[[#top | Top]]'''''
 
== Script 2 - Basic HTML ==
 
== Script 2 - Basic HTML ==
Line 99: Line 100:
 
{|
 
{|
 
|-
 
|-
|valign="top"|   
+
|valign=&quot;top&quot;|   
<pre>
+
&lt;pre&gt;
 
#!/usr/bin/perl
 
#!/usr/bin/perl
  
 
# test_2.pl - Second Perl Script!
 
# test_2.pl - Second Perl Script!
print "Content-type: text/html\r\n\r\n";
+
print &quot;Content-type: text/html\r\n\r\n&quot;;
  
print "<HTML>";
+
print &quot;&lt;HTML&gt;&quot;;
print "<HEAD>";
+
print &quot;&lt;HEAD&gt;&quot;;
print "<TITLE>Hello World</TITLE>";
+
print &quot;&lt;TITLE&gt;Hello World&lt;/TITLE&gt;&quot;;
print "</HEAD>";
+
print &quot;&lt;/HEAD&gt;&quot;;
print "<BODY>";
+
print &quot;&lt;BODY&gt;&quot;;
print "<H1>Hello World</H1>";
+
print &quot;&lt;H1&gt;Hello World&lt;/H1&gt;&quot;;
print "</BODY>";
+
print &quot;&lt;/BODY&gt;&quot;;
print "</HTML>";
+
print &quot;&lt;/HTML&gt;&quot;;
</pre>
+
&lt;/pre&gt;
 
|
 
|
&nbsp;
+
&amp;nbsp;
|valign="top"|
+
|valign=&quot;top&quot;|
 
The code is similar to the above includes a shebang, comment and header line.
 
The code is similar to the above includes a shebang, comment and header line.
  
Line 126: Line 127:
 
* Copy this file to folder: '''UniServer\udrive\cgi-bin'''
 
* Copy this file to folder: '''UniServer\udrive\cgi-bin'''
 
* Start the servers.
 
* Start the servers.
* Type the following into a browser: '''<nowiki>http://localhost/cgi-bin/test_2.pl</nowiki>'''  
+
* Type the following into a browser: '''&lt;nowiki&gt;http://localhost/cgi-bin/test_2.pl&lt;/nowiki&gt;'''  
  
 
A page full of print statements becomes very tedious the next script makes the task a little easier.  
 
A page full of print statements becomes very tedious the next script makes the task a little easier.  
Line 136: Line 137:
 
{|
 
{|
 
|-
 
|-
|valign="top"|   
+
|valign=&quot;top&quot;|   
<pre>
+
&lt;pre&gt;
 
#!/usr/bin/perl
 
#!/usr/bin/perl
  
 
# test_3.pl - Third Perl Script!
 
# test_3.pl - Third Perl Script!
print "Content-type: text/html\r\n\r\n";
+
print &quot;Content-type: text/html\r\n\r\n&quot;;
  
print <<"EOF123";
+
print &lt;&lt;&quot;EOF123&quot;;
<HTML>
+
&lt;HTML&gt;
  <HEAD>
+
  &lt;HEAD&gt;
   <TITLE>Hello World</TITLE>
+
   &lt;TITLE&gt;Hello World&lt;/TITLE&gt;
  </HEAD>
+
  &lt;/HEAD&gt;
  <BODY>
+
  &lt;BODY&gt;
   <H1>Hello World</H1>
+
   &lt;H1&gt;Hello World&lt;/H1&gt;
  </BODY>
+
  &lt;/BODY&gt;
</HTML>
+
&lt;/HTML&gt;
 
EOF123
 
EOF123
</pre>
+
&lt;/pre&gt;
 
|
 
|
&nbsp;
+
&amp;nbsp;
|valign="top"|
+
|valign=&quot;top&quot;|
 
With the exception of the header all print statements have been replaced with two special markers.
 
With the exception of the header all print statements have been replaced with two special markers.
  
A block of text to be printed is enclosed between''' print <<"EOF123";''' and '''EOF123''' start and end tags respectively.     
+
A block of text to be printed is enclosed between''' print &lt;&lt;&quot;EOF123&quot;;''' and '''EOF123''' start and end tags respectively.     
  
'''''Note 1'':''' There's nothing special about the "EOF123" string use anything you like however it must be identical in both cases.
+
'''''Note 1'':''' There's nothing special about the &quot;EOF123&quot; string use anything you like however it must be identical in both cases.
  
 
'''''Note 2'':''' The end tag '''EOF123''' must be place on its own line and no spaces are allowed at either the beging or end of the statement.
 
'''''Note 2'':''' The end tag '''EOF123''' must be place on its own line and no spaces are allowed at either the beging or end of the statement.
Line 169: Line 170:
 
* Copy this file to folder: '''UniServer\udrive\cgi-bin'''
 
* Copy this file to folder: '''UniServer\udrive\cgi-bin'''
 
* Start the servers.
 
* Start the servers.
* Type the following into a browser: '''<nowiki>http://localhost/cgi-bin/test_3.pl</nowiki>'''  
+
* Type the following into a browser: '''&lt;nowiki&gt;http://localhost/cgi-bin/test_3.pl&lt;/nowiki&gt;'''  
 
Using here-doc is a real time-saver.
 
Using here-doc is a real time-saver.
 
|}
 
|}
Line 177: Line 178:
  
 
== Script 4 - Basic HTML CGI.pm function-oriented ==
 
== Script 4 - Basic HTML CGI.pm function-oriented ==
CGI.pm has two faces either function-oriented or object-oriented. This example shows how to use the function interface. The command '''Use CGI''' takes a parameter this allows us to import a set of functions from the CGI module. This example imports the "'''standard'''" set of functions from this module.
+
CGI.pm has two faces either function-oriented or object-oriented. This example shows how to use the function interface. The command '''Use CGI''' takes a parameter this allows us to import a set of functions from the CGI module. This example imports the &quot;'''standard'''&quot; set of functions from this module.
  
 
{|
 
{|
 
|-
 
|-
|valign="top"|   
+
|valign=&quot;top&quot;|   
<pre>
+
&lt;pre&gt;
 
#!/usr/bin/perl
 
#!/usr/bin/perl
  
Line 192: Line 193:
 
       h1('Hello World'),        # level 1 header
 
       h1('Hello World'),        # level 1 header
 
       end_html;                  # end of HTML
 
       end_html;                  # end of HTML
</pre>
+
&lt;/pre&gt;
 
|
 
|
&nbsp;
+
&amp;nbsp;
|valign="top"|
+
|valign=&quot;top&quot;|
<br>'''''Running the script'''''
+
&lt;br&gt;'''''Running the script'''''
 
* Create a text file and copy the script. Save the file with name '''test_4.pl'''
 
* Create a text file and copy the script. Save the file with name '''test_4.pl'''
 
* Copy this file to folder: '''UniServer\udrive\cgi-bin'''
 
* Copy this file to folder: '''UniServer\udrive\cgi-bin'''
 
* Start the servers.
 
* Start the servers.
* Type the following into a browser: '''<nowiki>http://localhost/cgi-bin/test_4.pl</nowiki>'''  
+
* Type the following into a browser: '''&lt;nowiki&gt;http://localhost/cgi-bin/test_4.pl&lt;/nowiki&gt;'''  
 
|}
 
|}
 
The above is intended to provide a working example in no way does it indicate the enormity and flexibility of this module.
 
The above is intended to provide a working example in no way does it indicate the enormity and flexibility of this module.
Line 211: Line 212:
 
{|
 
{|
 
|-
 
|-
|valign="top"|   
+
|valign=&quot;top&quot;|   
<pre>
+
&lt;pre&gt;
 
#!/usr/bin/perl
 
#!/usr/bin/perl
  
Line 219: Line 220:
 
use CGI;                            # load CGI functions
 
use CGI;                            # load CGI functions
 
$q = new CGI;                        # create new CGI object
 
$q = new CGI;                        # create new CGI object
print $q->header,                    # create HTTP header
+
print $q-&gt;header,                    # create HTTP header
       $q->start_html('Hello World'), # start of HTML
+
       $q-&gt;start_html('Hello World'), # start of HTML
       $q->h1('Hello World'),        # level 1 header
+
       $q-&gt;h1('Hello World'),        # level 1 header
       $q->end_html;                  # end of HTML
+
       $q-&gt;end_html;                  # end of HTML
</pre>
+
&lt;/pre&gt;
 
|
 
|
&nbsp;
+
&amp;nbsp;
|valign="top"|
+
|valign=&quot;top&quot;|
<br>'''''Running the script'''''
+
&lt;br&gt;'''''Running the script'''''
 
* Create a text file and copy the script. Save the file with name '''test_5.pl'''
 
* Create a text file and copy the script. Save the file with name '''test_5.pl'''
 
* Copy this file to folder: '''UniServer\udrive\cgi-bin'''
 
* Copy this file to folder: '''UniServer\udrive\cgi-bin'''
 
* Start the servers.
 
* Start the servers.
* Type the following into a browser: '''<nowiki>http://localhost/cgi-bin/test_5.pl</nowiki>'''  
+
* Type the following into a browser: '''&lt;nowiki&gt;http://localhost/cgi-bin/test_5.pl&lt;/nowiki&gt;'''  
 
|}
 
|}
 
Again the objective is to provide a working example. The above gives you some idea of the modules capabilities take a look at Perl's doc for more information.
 
Again the objective is to provide a working example. The above gives you some idea of the modules capabilities take a look at Perl's doc for more information.
Line 239: Line 240:
 
When a form is submitted its easy to pick-up the query string and process it. There is no need to use a form the query string can be included with the URL. This example demostrates the principal.
 
When a form is submitted its easy to pick-up the query string and process it. There is no need to use a form the query string can be included with the URL. This example demostrates the principal.
  
URL: '''<nowiki>http://localhost/cgi-bin/test_6.pl?part1=Hello&part2=World</nowiki>'''
+
URL: '''&lt;nowiki&gt;http://localhost/cgi-bin/test_6.pl?part1=Hello&amp;part2=World&lt;/nowiki&gt;'''
  
 
{|
 
{|
 
|-
 
|-
|valign="top"|   
+
|valign=&quot;top&quot;|   
<pre>
+
&lt;pre&gt;
 
#!/usr/bin/perl
 
#!/usr/bin/perl
  
Line 252: Line 253:
 
print header,              # create HTTP header
 
print header,              # create HTTP header
 
   start_html('Hello Page'); # start of HTML
 
   start_html('Hello Page'); # start of HTML
   my $p1 = param("part1");  # get first parameter   
+
   my $p1 = param(&quot;part1&quot;);  # get first parameter   
   my $p2 = param("part2");  # get second parameter   
+
   my $p2 = param(&quot;part2&quot;);  # get second parameter   
print  h1($p1." ".$p2);    # level 1 header
+
print  h1($p1.&quot; &quot;.$p2);    # level 1 header
 
print  end_html;            # end of HTML
 
print  end_html;            # end of HTML
</pre>
+
&lt;/pre&gt;
 
|
 
|
&nbsp;
+
&amp;nbsp;
|valign="top"|
+
|valign=&quot;top&quot;|
<br>'''''Running the script'''''
+
&lt;br&gt;'''''Running the script'''''
 
* Create a text file and copy the script. Save the file with name '''test_6.pl'''
 
* Create a text file and copy the script. Save the file with name '''test_6.pl'''
 
* Copy this file to folder: '''UniServer\udrive\cgi-bin'''
 
* Copy this file to folder: '''UniServer\udrive\cgi-bin'''
 
* Start the servers.
 
* Start the servers.
* Type the following into a browser:<br> '''<nowiki>http://localhost/cgi-bin/test_6.pl?part1=Hello&part2=World</nowiki>'''  
+
* Type the following into a browser:&lt;br&gt; '''&lt;nowiki&gt;http://localhost/cgi-bin/test_6.pl?part1=Hello&amp;part2=World&lt;/nowiki&gt;'''  
 
|}
 
|}
The query string '''?part1=Hello&part2=World''' contains two name/value pairs  '''part1=Hello''' and '''part2=World'''. These values would normally be entered into a form using input tags and added to a URL when the page (form) is submitted.
+
The query string '''?part1=Hello&amp;part2=World''' contains two name/value pairs  '''part1=Hello''' and '''part2=World'''. These values would normally be entered into a form using input tags and added to a URL when the page (form) is submitted.
  
The script picks-up our two values using CGI function '''param("input tag name")'''and assigns them to two variables '''$p1''' and '''£p2'''. The two variables (strings) are concatenated (joined together) and printed.
+
The script picks-up our two values using CGI function '''param(&quot;input tag name&quot;)'''and assigns them to two variables '''$p1''' and '''£p2'''. The two variables (strings) are concatenated (joined together) and printed.
  
 
'''''[[#top | Top]]'''''
 
'''''[[#top | Top]]'''''
Line 276: Line 277:
 
{|
 
{|
 
|-
 
|-
|valign="top"|   
+
|valign=&quot;top&quot;|   
<pre>
+
&lt;pre&gt;
 
#!/usr/bin/perl
 
#!/usr/bin/perl
  
Line 283: Line 284:
  
 
use CGI qw/:standard/;                                # load standard CGI routines
 
use CGI qw/:standard/;                                # load standard CGI routines
   my $p1 = param("part1");                            # get parameter   
+
   my $p1 = param(&quot;part1&quot;);                            # get parameter   
   my $p2 = param("part2");                            # get parameter   
+
   my $p2 = param(&quot;part2&quot;);                            # get parameter   
   my $p3 = param("part3");                            # get parameter   
+
   my $p3 = param(&quot;part3&quot;);                            # get parameter   
 
print header,                                          # create HTTP header
 
print header,                                          # create HTTP header
 
   start_html('Hello Page'),                            # start of HTML
 
   start_html('Hello Page'),                            # start of HTML
 
   h1('Simple form');                                  # level h1 header
 
   h1('Simple form');                                  # level h1 header
if ($p1 && $p2 ){                                      # check both set  
+
if ($p1 &amp;&amp; $p2 ){                                      # check both set  
   print p('Full name = '.$p1." ".$p2);                # print variables
+
   print p('Full name = '.$p1.&quot; &quot;.$p2);                # print variables
 
   print p('Extra info = '.$p3);                        # print variable
 
   print p('Extra info = '.$p3);                        # print variable
 
}
 
}
Line 296: Line 297:
 
print p('Enter First Name : ', textfield('part1','')); # add input tag
 
print p('Enter First Name : ', textfield('part1','')); # add input tag
 
print p('Enter Last Name  : ', textfield('part2','')); # add input tag
 
print p('Enter Last Name  : ', textfield('part2','')); # add input tag
print p('Extra:','&nbsp;' x 18 ,popup_menu('part3',        # create dropdown menu
+
print p('Extra:','&amp;nbsp;' x 18 ,popup_menu('part3',        # create dropdown menu
 
['Hello World 1','Hello World 2','Hello World 3']));  # menu values
 
['Hello World 1','Hello World 2','Hello World 3']));  # menu values
 
print p(submit('Send'));                              # add submit button
 
print p(submit('Send'));                              # add submit button
 
print end_form(),hr();                                # end form
 
print end_form(),hr();                                # end form
 
print  end_html;                                      # end of HTML
 
print  end_html;                                      # end of HTML
</pre>
+
&lt;/pre&gt;
 
|}
 
|}
 
'''''Running the script'''''
 
'''''Running the script'''''
Line 307: Line 308:
 
* Copy this file to folder: '''UniServer\udrive\cgi-bin'''
 
* Copy this file to folder: '''UniServer\udrive\cgi-bin'''
 
* Start the servers.
 
* Start the servers.
* Type the following into a browser: '''<nowiki>http://localhost/cgi-bin/test_7.pl</nowiki>'''  
+
* Type the following into a browser: '''&lt;nowiki&gt;http://localhost/cgi-bin/test_7.pl&lt;/nowiki&gt;'''  
  
 
'''''[[#top | Top]]'''''
 
'''''[[#top | Top]]'''''
Line 316: Line 317:
 
For example to run '''test_1.pl''' copy it to folder '''www''' type the following into your browser:
 
For example to run '''test_1.pl''' copy it to folder '''www''' type the following into your browser:
  
'''<nowiki>http://localhost/test_1.pl</nowiki>'''
+
'''&lt;nowiki&gt;http://localhost/test_1.pl&lt;/nowiki&gt;'''
  
 
This is possible because cgi has been enabled in file '''.htaccess''' which is located in www. Open the file in a text editor you will find these two lines they have been un-commented (hash removed) hence enabled:
 
This is possible because cgi has been enabled in file '''.htaccess''' which is located in www. Open the file in a text editor you will find these two lines they have been un-commented (hash removed) hence enabled:
  
<pre>
+
&lt;pre&gt;
 
AddHandler cgi-script .pl .cgi
 
AddHandler cgi-script .pl .cgi
 
Options +ExecCGI
 
Options +ExecCGI
</pre>
+
&lt;/pre&gt;
  
 
The first line informs Apache files with the specified extension are to be processed as cgi scripts.
 
The first line informs Apache files with the specified extension are to be processed as cgi scripts.

Revision as of 01:07, 24 November 2010

This Page Is Currently Under Construction And Will Be Available Shortly, Please Visit Reserve Copy Page

<span id="top"></span>

Perl CGI - Hello World

Introduction

This step-by-step guide shows a small fraction of Perl’s CGI power. It covers some core Perl functions and modules.

I have kept these scripts simple and show how to run them on Uniform Server.

Shebang

Every Perl script starts with a special line known in the Unix world as the Shebang line.

Shebang &nbsp; Notes

<pre>#!/usr/bin/perl</pre>

&nbsp;

It has the following format: Starts with a hash "<nowiki>#</nowiki>" followed by an exclamation mark "!" and then the complete path on your system to the Perl program itself.

The shebang shown corresponds to Uniform Server running either in portable-mode (basic) or disk-root. The line informs Apache where to find the Perl program, "/" means start at the top level of a disk then follow the folder path usr, bin and finally the name of the Perl program perl.exe note the file extension is assumed.

<pre>#!c:/UniServer/usr/bin/perl</pre>

&nbsp;

When Uniform Server is installed as a service all Perl shebangs are changed to match the installation path. An example of this shebang is shown for a default installation of Mona installed as a service. Hence when writing new scripts remember to use the correct path for the shebang.

Note 1: The shebang can take parameters the most useful is -w it enables warnings remove it on finished scripts.

  • <nowiki>#!/usr/bin/perl -w</nowiki>
  • <nowiki>#!c:/UniServer/usr/bin/perl -w</nowiki>

Note 2: Forward slashes are Unix paths if you wish you can use a back slash the path must be enclosed in quotes.

  • <nowiki>#!"\usr\bin\perl"</nowiki>
  • <nowiki>#!"c:\UniServer\usr\bin\perl"</nowiki>

Note 3: For maximum computability always use forward slashes and run Uniform Server in portable or disk-root mode.

Top

Content-type headers

The first thing a CGI script must perform is to output a header. This header is checked by Apache and then passed on to a users browser informing it what type of file to expect. In the hello world examples we are outputting an HTML file hence the header looks like this:

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

&nbsp;

Its important to output it exactly as shown. Must start with a capital "C" followed by lowercase characters. Of importance are the two newline characters (\n\n) at the end of the header. The header needs to be followed by a blank line hence the second newline character.

<pre>print "Content-type: text/html\r\n\r\n";</pre>

&nbsp;

The above works fine on Windows.

On some Unix boxes it fails hence for compatibility between Windows and Unix add \r before each \n.

Top

Script 1 - Basic

Understanding the above two lines is important and allows us to look at the first hello world script:

<pre>

  1. !/usr/bin/perl
  1. test_1.pl - First Perl Script!

print "Content-type: text/html\r\n\r\n"; print "Hello World\n"; # Comment starts </pre>

&nbsp;

The first line is the shebang informing Apache where to find the Perl program.

The second line starts with a hash "#" indicating the start of a comment, any character after this up to the end of a line are ignored. Although the shebang starts with a hash it is not a comment because it is combined with an exclamation mark the two together define a shebang. You can start a comment anywhere along a line, if a line is Perl code a comment must start after the line terminator character ";" semi-column.

The third lines outputs (prints) the header.

Last line prints Hello World, anything to be printed is placed in quotes, all code lines are terminated with a semi-column. If you wish add a comment after the line (code) terminator.

Running the script

  • Create a text file and copy the above script. Save the file with name test_1.pl
  • Copy this file to folder: UniServer\udrive\cgi-bin
  • Start the servers.
  • Type the following into a browser: <nowiki>http://localhost/cgi-bin/test_1.pl</nowiki>

Top

Script 2 - Basic HTML

In reality we have lied to a browser what is served resembles nothing like an HTML page. A browser will have worked overtime to render the above.

The next script addresses this issue:

<pre>

  1. !/usr/bin/perl
  1. test_2.pl - Second Perl Script!

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

print "<HTML>"; print "<HEAD>"; print "<TITLE>Hello World</TITLE>"; print "</HEAD>"; print "<BODY>"; print "<H1>Hello World</H1>"; print "</BODY>"; print "</HTML>"; </pre>

&nbsp;

The code is similar to the above includes a shebang, comment and header line.

Each piece of HTML code is individually output using a print statement.

Running the script

  • Create a text file and copy the script. Save the file with name test_2.pl
  • Copy this file to folder: UniServer\udrive\cgi-bin
  • Start the servers.
  • Type the following into a browser: <nowiki>http://localhost/cgi-bin/test_2.pl</nowiki>

A page full of print statements becomes very tedious the next script makes the task a little easier.

Top

Script 3 - Basic HTML Here-doc

I have taken the above code and reduce the number of print statements required using a short cut known as Here-document quoting.

<pre>

  1. !/usr/bin/perl
  1. test_3.pl - Third Perl Script!

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

print <<"EOF123"; <HTML>

<HEAD>
  <TITLE>Hello World</TITLE>
</HEAD>
<BODY>
  <H1>Hello World</H1>
</BODY>

</HTML> EOF123 </pre>

&nbsp;

With the exception of the header all print statements have been replaced with two special markers.

A block of text to be printed is enclosed between print <<"EOF123"; and EOF123 start and end tags respectively.

Note 1: There's nothing special about the "EOF123" string use anything you like however it must be identical in both cases.

Note 2: The end tag EOF123 must be place on its own line and no spaces are allowed at either the beging or end of the statement.

Running the script

  • Create a text file and copy the script. Save the file with name test_3.pl
  • Copy this file to folder: UniServer\udrive\cgi-bin
  • Start the servers.
  • Type the following into a browser: <nowiki>http://localhost/cgi-bin/test_3.pl</nowiki>

Using here-doc is a real time-saver.

It is possible to write complex scripts using Perl’s core functions however to unleash its real power you will want to use modules. There are no shortages of these the next two scripts use one of Perl’s most powerful modules CGI.pm.

Top

Script 4 - Basic HTML CGI.pm function-oriented

CGI.pm has two faces either function-oriented or object-oriented. This example shows how to use the function interface. The command Use CGI takes a parameter this allows us to import a set of functions from the CGI module. This example imports the "standard" set of functions from this module.

<pre>

  1. !/usr/bin/perl
  1. test_4.pl - Fourth Perl Script!

use CGI qw/:standard/; # load standard CGI routines print header, # create HTTP header

     start_html('Hello World'), # start of HTML
     h1('Hello World'),         # level 1 header
     end_html;                  # end of HTML

</pre>

&nbsp;

<br>Running the script

  • Create a text file and copy the script. Save the file with name test_4.pl
  • Copy this file to folder: UniServer\udrive\cgi-bin
  • Start the servers.
  • Type the following into a browser: <nowiki>http://localhost/cgi-bin/test_4.pl</nowiki>

The above is intended to provide a working example in no way does it indicate the enormity and flexibility of this module.

Top

Script 5 - Basic HTML CGI.pm object-oriented

This next example shows the second face of this module which is object-oriented. Again it only scratches the surface, You can create one or more CGI objects and then use object methods to create various elements of a page.

<pre>

  1. !/usr/bin/perl
  1. test_5.pl - Fifth Perl Script!

use CGI; # load CGI functions $q = new CGI; # create new CGI object print $q->header, # create HTTP header

     $q->start_html('Hello World'), # start of HTML
     $q->h1('Hello World'),         # level 1 header
     $q->end_html;                  # end of HTML

</pre>

&nbsp;

<br>Running the script

  • Create a text file and copy the script. Save the file with name test_5.pl
  • Copy this file to folder: UniServer\udrive\cgi-bin
  • Start the servers.
  • Type the following into a browser: <nowiki>http://localhost/cgi-bin/test_5.pl</nowiki>

Again the objective is to provide a working example. The above gives you some idea of the modules capabilities take a look at Perl's doc for more information.

Top

Script 6 - Basic HTML CGI.pm query string

When a form is submitted its easy to pick-up the query string and process it. There is no need to use a form the query string can be included with the URL. This example demostrates the principal.

URL: <nowiki>http://localhost/cgi-bin/test_6.pl?part1=Hello&part2=World</nowiki>

<pre>

  1. !/usr/bin/perl
  1. test_6.pl - Sixth Perl Script!

use CGI qw/:standard/; # load standard CGI routines print header, # create HTTP header

 start_html('Hello Page'); # start of HTML
 my $p1 = param("part1");  # get first parameter   
 my $p2 = param("part2");  # get second parameter   

print h1($p1." ".$p2); # level 1 header print end_html; # end of HTML </pre>

&nbsp;

<br>Running the script

The query string ?part1=Hello&part2=World contains two name/value pairs part1=Hello and part2=World. These values would normally be entered into a form using input tags and added to a URL when the page (form) is submitted.

The script picks-up our two values using CGI function param("input tag name")and assigns them to two variables $p1 and £p2. The two variables (strings) are concatenated (joined together) and printed.

Top

Script 7 - Basic HTML CGI.pm form

Generally you would combine a form and its processing in a single script. CGI.pm makes the whole task very easy, this example shows some of the form functions. The form consists of two input fields a drop-down menu and send button.

<pre>

  1. !/usr/bin/perl
  1. test_7.pl - Seventh Perl Script!

use CGI qw/:standard/; # load standard CGI routines

 my $p1 = param("part1");                             # get parameter   
 my $p2 = param("part2");                             # get parameter   
 my $p3 = param("part3");                             # get parameter   

print header, # create HTTP header

 start_html('Hello Page'),                            # start of HTML
 h1('Simple form');                                   # level h1 header

if ($p1 && $p2 ){ # check both set

 print p('Full name = '.$p1." ".$p2);                 # print variables
 print p('Extra info = '.$p3);                        # print variable

} print hr, start_form; # start form print p('Enter First Name : ', textfield('part1',)); # add input tag print p('Enter Last Name : ', textfield('part2',)); # add input tag print p('Extra:','&nbsp;' x 18 ,popup_menu('part3', # create dropdown menu ['Hello World 1','Hello World 2','Hello World 3'])); # menu values print p(submit('Send')); # add submit button print end_form(),hr(); # end form print end_html; # end of HTML </pre>

Running the script

  • Create a text file and copy the script. Save the file with name test_7.pl
  • Copy this file to folder: UniServer\udrive\cgi-bin
  • Start the servers.
  • Type the following into a browser: <nowiki>http://localhost/cgi-bin/test_7.pl</nowiki>

Top

Web Root - Perl

You are not confined to running Perl scripts from folder cgi-bin you can copy the scripts to folder UniServer\udrive\www and run them from there.

For example to run test_1.pl copy it to folder www type the following into your browser:

<nowiki>http://localhost/test_1.pl</nowiki>

This is possible because cgi has been enabled in file .htaccess which is located in www. Open the file in a text editor you will find these two lines they have been un-commented (hash removed) hence enabled:

<pre> AddHandler cgi-script .pl .cgi Options +ExecCGI </pre>

The first line informs Apache files with the specified extension are to be processed as cgi scripts.

Last line gives Apache permission to execute cgi scripts.

Top

Summary

Perl is vast and very powerful this page was intended to provide a starting point. The main aim was to show how to run Perl scripts on Uniform Server by using working examples. With working examples you hack them around to meet your own needs.

Related Links:

New Users: Quick Perl CGI

New Users: Quick Perl CLI

Top