FIT3084: Perl CGI Scripts


In the previous lecture:

In this lecture:


References:


Perl at light speed




Datatypes & Variables





Input and Output


Expressions


Functions / Subroutines

Functions are declared and called as illustrated by this simple example.

#!/usr/monash/bin/perl -w
$val1 = 7;
$val2 = 9;

$answer = &maximum($val1, $val2);      # assign global $answer to maximum of 9 and 7
                                       # use the '&' symbol to call a function
print "answer = $answer\n";            # print the value of $answer

sub maximum                            # define a subroutine maximum
{
        my ($arg1, $arg2) = @_;        # receive the arguments passed in through @_
                                       # and place them in the local variables $arg1 & 2
        
        my ($result);                  # declare a local variable $result

        if ($arg1 >= $arg2)
        { $result = $arg1; }

        else
        { $result = $arg2; }

        return $result;                # return $result
}


Mark tallying example

Suppose we have a list of student names and their assignment scores:

Noel 25
Ben 76
Clementine 49
Norm 66
Chris 92
Doug 42
Carol 25
Ben 12
Clementine 0
Norm 66
Ben 9

 

Consider the following Perl program:

#!/usr/monash/bin/perl -w
open (GRADES, "grades") or die "Can't open grades: $!\n";

while ($line = <GRADES>) {
	($student, $grade) = split(" ", $line);
	$grades{$student} .= $grade . " ";
}

foreach $student (sort keys %grades) {
	$scores = 0;
	$total = 0;
	@grades = split(" ", $grades{$student});
	foreach $grade (@grades) {
		$total += $grade;
		$scores++;
	}
	$average = $total / $scores;
	print "$student: $grades{$student}\tAverage: $average\n";
}

 

In your own time:

Run the program on your local account and look at the results. Modify the script so the results are displayed on a web page via CGI.



A Calendar Perl CGI Script

#!/usr/bin/perl
# A calendar script

$CAL = '/usr/bin/cal';
$YEAR = 2001;

# fetch the text of the calendar using the unix cal command
# and chop off the newline character at the end of the returned string
chop($calendar_text = `$CAL $YEAR`);

#print the output html document
print <<END
Content-type: text/html

<HTML>
<HEAD>
	<TITLE>HAL's Calendar</TITLE>
</HEAD>

<BODY bgcolor="#ffffff" text="#000000">
	<BR>
		<B>Hi Dave!</B>
	<BR>
		Here's the calendar you requested.
	<BR>
		Love HAL.
		
	<PRE>
	$calendar_text
	</PRE>
	
	<A HREF="~aland/notes/lect18.html">lecture 18</A>
</BODY>
</HTML>

END


Run the calendar script.



Random Location Perl CGI Script


#!/usr/monash/bin/perl
# randomFile.pl

$FILE_DIRECTORY = 'http://www.cs.monash.edu.au/~aland/notes/randomFiles';
$MAXIMUM = 1000;
$NUMBER_OF_FILES = 3;

#set random seed and select a random file name

srand(time);
$number = int(rand($MAXIMUM));
$number = $number % $NUMBER_OF_FILES;

#return the location of this file to the browser

print "Location: $FILE_DIRECTORY/file$number.html\n\n";



Run the random file script.



Print Environment Variables Perl CGI Script

#!/usr/monash/bin/perl
# print environment variables

&print_HTTP_header;
&print_head;
&print_body;
&print_tail;

# ---- print the HTTP content-type header
# ---- 
sub print_HTTP_header
{
	print "Content-type: text/html\n\n";
}

#  ---- print HTML stuff at head
sub print_head
{
	print <<END;
	<HTML><HEAD>
	<TITLE>Environment Variables</TITLE>
	<BODY bgcolor="#ffffff" text="#000000">
	<H4>Environment Variables</H4>
END
}

# ---- loop through env var's and print them
# ---- 
sub print_body
{
	foreach $env_var (sort keys %ENV)
	{
		print "<STRONG>$env_var:</STRONG> $ENV{$env_var}<BR>\n";
	}
}

# ---- print HTML stuff at tail
# ---- 
sub print_tail
{
	print "<BR><BR>";
	print "<A HREF = \"/~aland/notes/lect18.html\">lecture 18</A>";
	print "</BODY></HTML>";
}


Run the print environment variables script.

Here is the HTML SRC for the call:

<A HREF="/cgi-bin/cgiwrap/~aland/printenv.pl/some/path/stuff?some+query+stuff">

Note the extra path info and the query string.


CGI.pm

Example (from perl doc):

#!/usr/monash/bin/perl

use CGI qw(:standard);

print header;
print start_html('A Simple Example'),
    h1('A Simple Example'),
    start_form,
    "What's your name? ",textfield('name'),
    p,
    "What's the combination?",
    p,
    checkbox_group(-name=>'words',
                   -values=>['eenie','meenie','minie','moe'],
                   -defaults=>['eenie','minie']),
    p,
    "What's your favorite color? ",
    popup_menu(-name=>'color',
               -values=>['red','green','blue','chartreuse']),
    p,
    submit,
    end_form,
    hr;

if (param()) {
    print 
        "Your name is",em(param('name')),
        p,
        "The keywords are: ",em(join(", ",param('words'))),
        p,
        "Your favorite color is ",em(param('color')),
        hr;
}
print end_html;

 

#!/usr/local/bin/perl
use CGI qw/:standard/;
print header(),
start_html(-title=>'Wow!'),
h1('Wow!'),
'Look Ma, no hands!',
end_html();
This code uses the cgi module in "function style" where its routines are brought into the standard namespace.

 

#!/usr/local/bin/perl
use CGI;
$q = new CGI;
print $q->header(),
$q->start_html(-title=>'Wow!'),
$q->h1('Wow!'),
'Look Ma, no hands!',
$q->end_html();
This code uses the cgi module in "object oriented style" where its routines are accessed through an "object" (CGI).

For more information see: http://stein.cshl.org/WWW/CGI/.


Where to find more:

This Page of Perl Pearls is only the bare minimum required to understand the examples given in lectures.


Please read a book or website on Perl to become more familiar with the language. Above all, practice writing a few Perl scripts!

Perl web sites:



This lecture's key point(s):


Courseware | Lecture notes

©Copyright Alan Dorin 2009