Biological Databases1/27/09

Using Perl CGI

Full documentation at

This description adapted from

For further reference on HTML try:

To use the Perl C module, start your program as below. $q is the CGI object. All statements of the form $q->something produce a string which contains HTML tags and additional information. Typically, you will print this. Here is how you create a simple "Hello World" HTML page:

#!/usr/bin/perl –w

use CGI qw(:standard); # load standard CGI routines

$q = new CGI; # create new CGI object

print $q->header('text/html'), # create the HTTP header

$q->start_html('hello world'), # start the HTML

$q->h1('hello world'), # produces large font

$q->end_html; # end the HTML

Most CGI.pm routines (what follows the $q->) accept several arguments. All routines use a named argument calling style that looks like this:

print $q->header(-type=>'image/gif',-expires=>'+3d');

Each argument name is preceded by a dash. Neither case nor order matters in the argument list. Several routines are commonly called with just one argument. In the case of these routines you can provide the single argument without an argument name. header() happens to be one of these routines. In this case, the single argument is the document type.

print $q->header('text/html');

CREATING A NEW QUERY OBJECT:

$q = new CGI;

This will parse the input data (from both POST and GET methods) and store it into $q. Note that when your program is called the first time (i.e., before a user enters the form data) there is no data.

GENERATING DYNAMIC DOCUMENTS

Most of CGI.pm's functions deal with creating documents on the fly. Generally you will produce the HTTP header first, followed by the document itself. The HTTP header tells the browser what type of document to expect.

print $q->header(‘text/html’);

The start_html() routine creates the <HTML> tag and the <body> tag. Note below that the start_html routine uses the page title parameter which puts the title on the browser tab.

print $q->start_html(-title=>’Secrets of CGI’);

The end_html() routine ends an HTML document by printing the </body</html> tags and indicates that the document should be sent to the user’s browser. It has no arguments.

print $q->end_html;

CREATING STANDARD HTML ELEMENTS:

A large number of routines in CGI.pm are "HTML shortcuts," routines that generate HTML tags for use in dynamically-generated pages. HTML tags have 1) attribute-value pairs which must appear within curly braces, and 2) contents, which are the words that appear on the web page, such as the words next to radio-button choices or the words in a link. The HTML shortcuts accept zero, one, or multiple arguments. If you provide no arguments, you get a single tag. Here are some examples:

print $q->Code //where Code is one of the following

Code Generated HTML

------

h1 <h1>

h1('some','contents'); <h1>some contents</h1>

br <br>

Code for clickable words:

print $q->a({-href=>'bioed.bu.edu/students_09/yourname/help.page.html',

-target=>'_help'},"Help");

Generated HTML:

<a href=

target="_help">Help</a>

In the previous example, the word Help is clickable. It will cause a new browser window to open to display a static html help page (static in this case because the file name ends in .html). Note that the argument to –target, _help, is merely a name given to the new browser window (which shows up in the tab on the browser). If this window is not open, a new window is created. If it is already open and the user clicks another href with the same target, the information will appear in the existing window. This can sometimes be confusing to users because they expect a new window to open up and it seems as though nothing is happening.

Code for an image to be displayed as part of the html page:

print $q->img({-src=>''

-align=>'LEFT'});

Generated HTML:

<img align="LEFT" src="'

Note that for the –href and -src, it is best to specify the entire path and file name (example: should check with the system administrator to find out how to correctly address files on the server.

THE DISTRIBUTIVE PROPERTY OF HTML SHORTCUTS

If you give the shortcut an argument consisting of a reference to a list, the tag will be distributed across each element of the list. For example, here's one way to make an unordered list:

print $q->ul(

li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy'])

);

Note that the types for unordered list are disc (a small filled circle), circle ( a small open circle), and square (a small filled square). This example will result in HTML output that looks like this:

<ul>

<li type="disc">Sneezy</li>

<li type="disc">Doc</li>

<li type="disc">Sleepy</li>

<li type="disc">Happy</li>

</ul>

This is extremely useful for creating tables. For example:

print $q->table({-border=>undef},

caption('When Should You Eat Your Vegetables?'),

Tr({-align=>CENTER,-valign=>TOP},

[

th(['Vegetable', 'Breakfast','Lunch','Dinner']),

td(['Tomatoes' , 'no', 'yes', 'yes']),

td(['Broccoli' , 'no', 'no', 'yes']),

td(['Onions' , 'yes','yes', 'yes'])

]

)

);

Comment

A few HTML tags don't follow the standard pattern for various reasons. comment() generates an HTML comment (<!-- comment -->). Call it like

print $q->comment('here is my comment');

CREATING FILL-OUTFORMS:

STARTING AND ENDING A FORM

print $q->start_form(-method=>$method,

-action=>$action,

-enctype=>$encoding);

<... various form stuff ...>

print $q->endform;

start_form() will return a <form> tag with the optional method, action and form encoding that you specify. The defaults are:

method: POST

action: this perl script, i.e., the one creating the form

enctype: application/x-www-form-urlencoded

Start_form()'s enctype argument tells the browser how to package the various fields of the form before sending the form to the server. Two values are possible:

application/x-www-form-urlencoded

This is the older type of encoding. It is suitable for short fields containing text data.

multipart/form-data

This is the newer type of encoding. It enables the "file upload" feature. Forms that use this type of encoding are not easily interpreted by CGI scripts unless they use CGI.pm or another library designed to handle them.

For compatibility, the start_form() method uses the older form of encoding by default. If you want to use the newer form of encoding by default, you can call start_multipart_form() instead of start_form().

CREATING A TEXT FIELD

General note. The default values that you specify for the forms are only used the first time the script is invoked (when there is no query string). On subsequent invocations of the script (when there is a query string), the values returned in the query string are used even if they are blank. If you want the same value used each time the script is called, use the -override parameter. This forces the default value to be used.

print $q->textfield(-name=>'field_name',

-default=>'starting value',

-override=>1,

-size=>50,

-maxlength=>80);

textfield() will return a text input field. The last four parameters are optional, they specify the initial contents of the textfield, the “override” which forces the field to contain the ‘starting value’ string rather than what the user entered, the size of the field visible on the webpage, and the maximum length of the input string. When the form is processed, the value of the text field can be retrieved with:

$value = $q->param('field_name');

CREATING A MULTILINE TEXT FIELD

print $q->textarea(-name=>'multiline_field_name',

-default=>'starting value',

-rows=>10,

-columns=>50);

textarea() is a multiline text entry box. The starting value for the field can be long and contain multiple lines.

CREATING A FILE UPLOAD FIELD

print $q->filefield(-name=>'uploaded_file',

-size=>50,

-maxlength=>80);

filefield() will return a file upload field. In order for file transfer to work, you must use the multipart/form-data specification for the encytype in start-form(). To get a file handle for the temporary copy of the file that CGI.pm creates, use the upload() function. The file handle can be used to read the file as below:

$fh = $q->upload('uploaded_file');

while (<$fh>) {

print;

}

CREATING A POPUP MENU

print $q->popup_menu(-name=>'menu_name',

-values=>['eenie','meenie','minie'],

-default=>'meenie',

-labels=>\%labels);

the first two parameters are required. -default specifies which item in the menu is the default. If absent, it will be the first item. –labels is used if you want the visible item names to be different from their values. When the form is processed, the selected value of the popup menu can be retrieved using:

$popup_menu_value = $q->param('menu_name');

CREATING A STANDALONE CHECKBOX

print $q->checkbox(-name=>'checkbox_name',

-checked=>1,

-value=>'ON',

-label=>'CLICK ME');

–checked means the box will appear with a check (1) or not (0). –value is assigned to the parameter when the box is checked. –label is what appears next to the box. The value of the checkbox can be retrieved using:

$turned_on = $q->param('checkbox_name');

CREATING A RADIO BUTTON GROUP

print $q->radio_group(-name=>'group_name',

-values=>['eenie','meenie','minie'],

-default=>'meenie',

-linebreak=>'true',

-labels=>\%labels

radio_group() creates a set of logically-related radio buttons (turning one member of the group on turns the others off). The optional -linebreak can be set to true to place line breaks so the buttons appear as a vertical list. Otherwise, they will be strung together on a horizontal line. When the form is processed, the selected radio button can be retrieved using:

$which_radio_button = $q->param('group_name');

CREATING A SUBMIT BUTTON

print $q->submit(-name=>'button_name',

-value=>'value');

If you have multiple buttons on a page, you can figure out which button was pressed by using different values for each one:

$which_one = $q->param('button_name');

CREATING A HIDDEN FIELD

print $q->hidden(-name=>'hidden_name',

-default=>'value);

hidden() produces a text field that can't be seen by the user. It is useful for passing state variable information from one invocation of the script to the next. Fetch the value of a hidden field this way:

$hidden_value = $q->param('hidden_name');

CREATING A CLICKABLE IMAGE BUTTON

print $q->image_button(-name=>'button_name',

-src=>'/sourceURL',

-align=>'MIDDLE');

–src is the path to the image file. –align may be TOP, MIDDLE, or BOTTOM.

RETRIEVING CGI ERRORS

Errors can occur while processing user input, particularly when processing uploaded files. When these errors occur, CGI.pm will stop processing and return an empty parameter list. You can test for the existence and nature of errors using the cgi_error() function. The error messages are formatted as HTTP status codes. You can either incorporate the error text into an HTML page, or use it as the value of the HTTP status:

my $error = $q->cgi_error;

if ($error) {

print $q->header(-status=>$error),

$q->start_html('Problems'),

$q->h2('Request not processed'),

$q->strong($error),

$q->end_html;

exit 0;

};

Complete Program Using Perl CGI

#!/usr/bin/perl -w

use CGI qw(:standard);

$q=new CGI;

print

$q->header('text/html'),

$q->start_html,

$q->h1('first test'),

$q->a({-href=>' -target=>'_trdb'}, "TRDB"),

$q->br,

$q->a({-href=>'

-target=>'_new'},

"HTML Reference Table of Contents"),

$q->br,

$q->img({src=>'

$q->br,

$q->ul(

li({-type=>'circle'},['Sneezy','Doc','Sleepy','Happy'])

),

$q->table({-border=>undef},

caption('When Should You Eat Your Vegetables?'),

Tr({-align=>CENTER,-valign=>TOP},

[th(['Vegetable', 'Breakfast','Lunch','Dinner']),

td(['Tomatoes' , 'no', 'yes', 'yes']),

td(['Broccoli' , 'no', 'no', 'yes']),

td(['Onions' , 'yes','yes', 'yes'])

]));

print

$q->start_form(-method=>'POST',

-action=>'perl.test1.pl',

-enctype=>'application/x-www-form-urlencoded'),

$q->br,

"Enter your name:",

$q->br,

$q->textfield(-name=>'user_name',

-default=>'starting value',

-override=>1,

-size=>50,

-maxlength=>80),

$q->br,

"Enter your address:",

$q->br,

$q->textarea(-name=>'mailing_address',

-default=>'starting value',

-rows=>6,

-columns=>50),

$q->br,

$q->submit(-name=>'submit_button',

-value=>'submit'),

$q->endform,

$q->hr;

if ($q->param()) #tests if anything has been returned

{

my $user=param('user_name');

my $address=param('mailing_address');

print

"User: $user",

$q->br,

"Mailing address: $address",

$q->br,

$q->hr;

}

print

$q->end_html;