CGI.pm's scrolling_list() and popup_menu() methods can be hard to get the hang of. Even
though the others have answered your question, another question that you will likely ask is
how do you now use different labels for your values -- that is, instead of:
<option value="Fred">Fred</option>
<option value="Wilma">Wilma</option>
<option value="Dino">Dino</option>
You now want:
<option value="4">Fred</option>
<option value="5">Wilma</option>
<option value="9">Dino</option>
Sometimes, you wonder why you can't just say:
my %name = (Fred => 4, Wilma > 5, Dino => 9);
print scrolling_list(-name => 'list_name', -values => \%name);
And let it handle the mapping for you. There are reasons why you cannot do this:
- the -values parameter accepts an array ref or single scalar only
- hashes are not ordered
- do we want the hash keys to be the labels or the hash values? CGI.pm doesn't know!
and there may be other reasons. So, how to you achieve a select box that looks like:
<option value="4">Fred</option>
<option value="5">Wilma</option>
<option value="9">Dino</option>
First, we deiced what the values and labels are going to be. Originally, the values and
the labels were the same, but now the values are [4,5,9] and the labels
are [qw(Fred Wilma Dino)]. So the hash i provided above was backwards!
my %name = (Fred => 4, Wilma > 5, Dino => 9);
This is snag #1 ... make sure your hash keys are the values that will be passed to
-values. Let's reverse the hash by
hand:
my %name = (4 => 'Fred', 5 => 'Wilma', 9 => 'Dino');
Now we need to decide how to order. We'll pick alphabetical ordering by the labels. We
achieve this when we specify the -values attribute. Since that attrib wants an
array ref, we will need to construct one from our hash, %name. Here is one way
to do that:
my @value = sort { $name{$a} cmp $name{$b} } keys %name;
A bit daunting for newbies, but rest assured that the results are (9,4,5) - that is, the numbers will be ordered by their respective labels, alphabetically.
Since we have already done the work of 'lining up' our values to our labels, all we need do
to specify the -labels attribute is pass a reference to the hash. Here goes:
my %name = (4 => 'Fred', 5 => 'Wilma', 9 => 'Dino');
my @value = sort { $name{$a} cmp $name{$b} } keys %name;
print scrolling_list(
-name => 'list_name',
-values => \@value,
-labels => \%name,
);
And the result should be:
<select name="list_name" size="3">
<option value="9">Dino</option>
<option value="4">Fred</option>
<option value="5">Wilma</option>
</select>
Hope this helps. :)
|