CMPS 335 Advanced Web Publishing
Perl and CGI Programming
Subroutines
Individual statements are often gouped into logical units called
procedures. There are two major types of procedures used in
Perl: functions and subroutines. In general, system-defined
procedures are called functions and user-defined procedures are
subroutines. A subroutine may have operands called arguments or
parameters. Arguments are usually enclosed in parentheses and are
separated by commas if there are more than one. Like functions, a
subroutine also has an intrinsic final value called a return value.
The return value can be stored for later use. The default return
value is the value of the last expression evaluated.
Subroutines
are reusable programs that can be used as many times as needed simply by
referring to their names. Subroutines are extremely useful time-saving
devices in programming. Typical subroutines for CGI scripts do
common tasks such as parsing forms and printing out HTML headers.
The Parse_Form script performs important form-parsing task and is used as
a subroutine in many other Perl scripts.
The Parse_Form subroutine
sub Parse_Form {
if ($ENV{'REQUEST_METHOD'} eq 'GET') {
@pairs = split(/&/, $ENV{'QUERY_STRING'});
}
elsif ($ENV{'REQUEST_METHOD'} eq 'POST') {
read (STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
@pairs = split(/&/, $buffer);
if ($ENV{'QUERY_STRING'}) {
@getpairs = split(/&/, $ENV{'QUERY_STRING'});
push(@pairs,@getpairs);
}
}
else {
print "Content-type: text/html\n\n";
print "<br>Use POST or GET";
}
foreach $pair (@pairs) {
($key, $value) = split (/=/, $pair);
$key =~ tr/+/ /;
$value =~ tr/+/ /;
$key =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$value =~s///g;
if ($formdata{$key}) {
$formdata{$key} .= ", $value";
} else {
$formdata{$key} = $value;
}
}
}
1;
Return to CMPS 335 Home Page
Return to Web Site Home Page