A module is a collection of useful functions which you can use in your programs. They are written by Perl people worldwide, and distributed mostly through CPAN, the Comprehensive Perl Archive Network.
Perl modules save you heaps of time - by using a module, you save yourself from "reinventing the wheel". Perl modules also tend to save you from making silly mistakes again and again while you try to figure out how to do a given task.
One common (but fiddly) task in CGI programming is taking the parameters given in an HTML form and turning them into variables that you can use.
The parameters from an HTML form are encoded in this "percent-encoded" format:
name=Kirrily&company=Netizen%20Pty.%20Ltd. |
If you use the POST method, these parameters are passed via STDIN to the CGI script, whereas GET passes them via the environment variable QUERY_STRING. This means that as well as simply parsing the character string, you need to know where to look for it as well.
The easiest way to parse this parameter line is to use CGI module.
Although it is part of the current Perl distribution, the CGI module is not documented in the Camel book. Instead, type perldoc CGI to read about it.
To use the CGI module, simply put the statement use CGI; at the top of your script, thus:
#!/usr/bin/perl -w use strict; use CGI; |
To accept form parameters into our CGI script as variables, we can say that we specifically want to use the params part of the CGI module:
#!/usr/bin/perl -w use strict; use CGI 'param'; |
This provides us with a new subroutine, param, which we can use to extract the value of the HTML form's fields.
#!/usr/bin/perl -w use strict; use CGI 'param'; my $name = param('name'); print "Content-type: text/html\n\n"; print "Hello, $name!"; |
When you run a CGI script from the command line, you will see a prompt like this:
(offline mode: enter name=value pairs on standard input) |
This allows you to enter parameters in the form name=value for testing and debugging purposes. Use CTRL-D (the Unix end-of-file character) to indicate that you are finished.
(offline mode: enter name=value pairs on standard input) name=fred age=40 ^D |
Write a simple form to ask the user for their name. Type in the above script and see if it works.
Add some fields to your form, including a checkbox and a drop down menu, and print out their values. What are the default true/false values for a checkbox?
What happens if you use the SELECT MULTIPLE form functionality? Try assigning that field's parameters from it to an array instead of a scalar, and you will see that the data is handled smoothly by the CGI module. Print them out using a foreach loop, as in earlier exercises.