Vous êtes sur la page 1sur 2

CGI functions

The CGI.pm module loads several special CGI functions for you. What are these functions? The first one, header(), is used to output any necessary HTTP headers before the script can display HTML output. Try taking this line out; you'll get an error from the Web server when you try to run it. This is another common source of bugs! The start_html() function is there for convenience. It returns a simple HTML header for you. You can pass parameters to it by using a hash, like this:
print $cgi->start_html( -title => "My document" );

(The end_html() method is similar, but outputs the footers for your page.) Finally, the most important CGI function is param(). Call it with the name of a form item, and a list of all the values of that form item will be returned. (If you ask for a scalar, you'll only get the first value, no matter how many there are in the list.)
$yourname = param("firstname"); print "<P>Hi, $yourname!</P>\n";

If you call param() without giving it the name of a form item, it will return a list of all the form items that are available. This form of param() is the core of our backatcha script:
for $i (param()) { print "<b>$i</b>: ", param($i), "<br>\n"; }

Remember, a single form item can have more than one value. You might encounter code like this on the Web site of a pizza place that takes orders over the Web:
<P>Pick your toppings!<BR> <INPUT TYPE=checkbox NAME=top VALUE=pepperoni> Pepperoni <BR> <INPUT TYPE=checkbox NAME=top VALUE=mushrooms> Mushrooms <BR> <INPUT TYPE=checkbox NAME=top VALUE=ham> Ham <BR> </P>

Someone who wants all three toppings would submit a form where the form item top has three values: "pepperoni," "mushrooms" and "ham." The server-side code might include this:
print "<P>You asked for the following pizza toppings: "; @top = param("top"); for $i (@top) { print $i, ". "; } print "</P>";

Now, here's something to watch out for. Take another look at the pizza-topping HTML code. Try pasting that little fragment into the backatcha form, just above the <INPUT TYPE=submit...> tag. Enter a favorite color, and check all three toppings. You'll see this:

favcolor: burnt sienna top: pepperonimushroomsham

Why did this happens? When you call param('name'), you get back a list of all of the values for that form item. This could be considered a bug in the backatcha.cgi script, but it's easily fixed - use join() to separate the item values:
print "<b>$i</b>: ", join(', ', param($i)), "<br>\n";

or call C<param()> in a scalar context first to get only the first value:
$j = param($i); print "<b>$i</b>: $j \n";

Always keep in mind that form items can have more than one value!

Vous aimerez peut-être aussi