- A CGI Shell
#!/usr/bin/perl #(1)
# Module which implements common CGI handling routines
require 'cgi-lib.cgi'; #(2)
# Initialization code goes here #(3)
#(4)
if ($ENV{'REQUEST_METHOD'} eq 'GET') { # Send them the form
# GET Method code goes here
} elsif ($ENV{'REQUEST_METHOD'} eq 'POST') { # Send them the form
# POST Method code goes here
} #POST
# Finalization Code goes here #(5)
# Sub-routines go here #(6)
# End of Program
- OS might require a path to the Perl interpreter
- Any require/use statements go here (cgi-lib.cgi is on the book's CD)
- Any common initialization code goes here.
- The GET method is the default and is usually sent to indicate that a form is to be returned. The POST method is usually returned after the form has been filled out and data needs to be passed to the module.
- Any common finalization code goes here.
- Keep all subroutines at the end for ease of maintenance.
- Hello World Example
#Hello World program
print <<EOF;
Content-type: text/html
<HTML>
<HEAD>
<TITLE>Hello World!</TITLE>
</HEAD>
<BODY>
Hello World!
</BODY>
</HTML>
EOF
;
- Hello World Example (with subroutines)
#Hello World program
require 'cgi-lib.cgi';
print &PrintHeader();
$title = 'Hello World!';
print &HtmlTop();
print "Hello World!\n";
print &HtmlBot();
# PrintHeader
# Returns the magic line which tells WWW that we're an HTML document
sub PrintHeader {
return "Content-type: text/html\n\n";
}
# HtmlTop
# Returns the head of an HTML document and the beginning of the body
sub HtmlTop {
local ($title) = @_;
return <<END_OF_TEXT;
<HTML>
<HEAD>
<TITLE>$title</TITLE>
</HEAD>
<BODY>
<H1>$title</H1>
END_OF_TEXT
;
}
# HtmlBot
# Returns the bottom of an HTML document
sub HtmlBot {
return "</BODY>\n</HTML>\n";
}
- "Hello World" Interactive
#Interactive Hello World program (uses CGI handling routines)
require 'cgi-lib.cgi';
$HtmlAction = 'hello.pl';
if (&MethGet()) { # send the form
print &PrintHeader();
$title = 'Hello World Interactive';
print &HtmlTop();
print <<EOT;
<FORM ACTION="$HtmlAction" METHOD=POST>
Please enter your first name:
<INPUT SIZE=20 NAME="fname"><P>
<INPUT TYPE=SUBMIT>
<INPUT TYPE=RESET>
</FORM>
EOT
;
print &HtmlBot();
}
elsif (&MethPost()) { # process the form
&ReadParse();
print &PrintHeader();
$title = 'Hello World Interactive';
print &HtmlTop();
print "Hello, &in{'fname'}!";
print &HtmlBot();
}
- Hello World Hello World (Source Code)
- Simple Array Example Simple Array Example (Source Code)
- Test Form for parsing Source code for parseform.cgi Unparsed text
These are links to documents that use perl scripts for file I/O