FIT3084: Perl
Programming
In the previous lecture:
In this lecture:
References:
Perl at light speed
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
}
|
A more complex example (from the Camel book):
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 = |
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.
CGI.pm
Example:
#!/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 |
This code uses the cgi module in "function style" where its routines are brought into the standard namespace. |
#!/usr/local/bin/perl |
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:
©Copyright Alan Dorin 2008