1. Home
  2. Computing & Technology
  3. Perl

Working with CGI.pm In-Depth
Creating Drop-Down Lists

by Kirk Brown
for About.com

Another handy form element is the drop-down list. This can offer a quick, clean selection method for the user. To create a drop-down list with Perl's CGI.pm, we start by assigning each item a value and a label in a hash called %labels. Of course, you can call it anything you'd like - but it's a good idea to keep the hash name related to it's contents. Let's look at an example:
my %labels = (
'yes' => 'For Sure!',
'no' => 'Not for me.',
'maybe' => 'Maybe So.');
The first part of each hash element (the hash's key) is the value of the list item. This is the thing that eventually will be POSTed to the form and your processing script. The second part of the has element (the hash's value) is the value of the list label. This is the part that the end user will see in the drop down menu. Without this label hash, the labels of each item on the list would default to the values themselves. Now that we've prepared a hash of labels, lets look at the rest of the script:
my %labels = (
'yes' => 'For Sure!',
'no' => 'Not for me.',
'maybe' => 'Maybe So.');

print $cgi->popup_menu(
-name => 'your_answer',
-values => ['yes','no','maybe'],
-default => 'yes',
-labels => \%labels
);
This produces the following output:
<select name="your_answer" >
<option selected="selected" value="yes">For Sure!</option>
<option value="no">Not for me.</option>
<option value="maybe">Maybe So.</option>
</select>
So, after setting our labels hash, we call the popup_menu function. We've seen the -name attribute in the general form attributes section. Next up is an array of drop-down list values. These should be the exact same values that make up the keys in the %labels hash. The -default value references the value of the list item that you want set active when the form is loaded.

Finally, the -labels hash is referenced via a pointer (notice the \ backslash in front of the call to the hash?). That's all you need for a simple drop-down list.

Explore Perl
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Perl
  4. CGI & Web
  5. Working with CGI.pm In-Depth - How to build a drop-down list with CGI.pm>

©2009 About.com, a part of The New York Times Company.

All rights reserved.