CGIs

Setup Notes

CGIs allow you to process HTML form data with perl. The basic structure for a CGI is as follows:

#! /usr/bin/perl use CGI qw(:standard); print "Content-type:text/html\n\n"; The CGI module that we are importing provides many nice features we will discuss below. The print line tells the browser what type of data we are sending. You MUST include this as your first line in order for the browser to show the text you print.

The CGI feature we covered is &param. This basically allows you to get the value out of a name value pair from an HTML form field. If you know the name of the form field, you can assign the value to a variable like this:

$x = &param('field_1');

where $x is the variable name, and field_1 is the name part of the name-value pair. &param will find whatever value goes with field_1 and sets that as the value fot $x. Practically, field_1 can be called anything you like. it just needs to be the name of a form field (ie input widget) in the form which calls this cgi.

We began covering subroutines as well. This allows you to move a section of code away from the main body. You can execute that code by using the name of the subroutine. For example:

#!/usr/bin/perl printTop(); sub printTop { print "Content-type: text/html\n\n"; print qq+ <html> <body bgcolor=white text=#000066> +; } This code has moved the printing we do for each HTML page into a subroutine called printTop. When we want to do everything inside the curly braces for the subroutine, we simply use the command printTop() in our perl code. Note that code in a subroutine will not execute unless we call the subroutine in the main code by doing printTop();