Wednesday, April 2, 2008

perl hash sort values example CGI script

In the following example what we are trying to do is to sort the Value part of the Hash and display it inside a popup menu sorted by the value rather than the key.



#!/usr/bin/perl
use CGI;

my $qry = CGI->new();

my %c = (
"1016"=>"W",
"1017"=>"Cl",
"1018"=>"Fu",
"1023"=>"Emerg",
"1024"=>"Responsibler",
"1025"=>"Director",
"1026"=>"Accountable"
);

$default = 1017;

my $html = $qry->popup_menu (

-name=>"XXX",
-values=>[sort { $c{$a} cmp $c{$b} } keys %c],
-labels=>\%c,
-override=>'true',
-default=> ( $default )

);

print $html;