in reply to Sorting by the hash value

While this is slightly off from your question. One thing about using CGI.pm that stinks is when you provide a hash so you can have different values and labels (as you are trying to do) it doesn't sort them. If this is why you are avoiding using CGI.pm you can use the snippet below that I use. It's a simple tie that you can use to make it sort by value.
package SortHash; #Kludge to get options sorted. use Tie::Hash; use vars qw(@ISA); @ISA = qw( Tie::StdHash ); sub FIRSTKEY { my $self = shift; @{ $self->{_SORTHASH_KEYS} } = sort {$self->{$a} cmp $self->{$b} } + grep { $_ ne '_SORTHASH_KEYS' } keys %{$self}; return shift @{ $self->{_SORTHASH_KEYS} }; } sub NEXTKEY { my $self = shift; return shift @{ $self->{_SORTHASH_KEYS} }; } package main; use CGI qw(:standard); my %list; tie %list, 'SortHash' ; # tied hash with sorted keys by value... print start_form; print popup_menu(-name=>'option' , labels=> \%list, -values=> [ keys % +list ] ); print end_form;


-Lee

"To be civilized is to deny one's nature."

Replies are listed 'Best First'.
Re: Re: Sorting by the hash value
by cybear (Monk) on Jul 29, 2002 at 10:32 UTC
    "To be civilized is to deny one's nature."
    Denying ones nature is the key to being human.

    Concerning "Sorting by the hash value":
    It is difficult to advise you without knowing exactly what
    you are trying to do, but if you are trying to print a
    sorted list of values couldn't you just:

    @keys = keys{%hash}; foreach $key (@keys) { $value = %hash{$key}; push(@values, $value); } sort(@values); print "@values\n";
      Are you replying to the root node? My kludge is to get around the fact that CGI.pm has the hash ordering (which is no order) when you use the -lables argument. I often need to use labels and tie'ing is easier than sublassing CGI.pm.

      As an aside, your code is overcomplicated.
      print sort values %hash;


      -Lee

      "To be civilized is to deny one's nature."
        Cool. I didn't know that you could do that.

        - cybear

      Isn't this supposed to be:
      @keys = keys{%hash}; foreach $key (@keys) { $value = $hash{$key}; # notice $ versus % here push(@values, $value); } sort(@values); print "@values\n";

      Otherwise, I think you get an error such as:
      Can't use subscript on private hash at foo.pl line 123, near "$key}" (Did you mean $ or @ instead of %?) BEGIN not safe after errors--compilation aborted at foo.pl line 123.