rapture has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I created this hash like this:
push @{$hash{$key}}, $val1, $val2, $val3
Now, I want to sort it based on the values of $val2, which is a number. I did this two years ago, lost the code, and know I need to do it again... woo is me. Can someone please refresh my memory?

Replies are listed 'Best First'.
Re: Sorting Hash
by Abigail-II (Bishop) on Aug 08, 2002 at 11:03 UTC
    You can't sort a hash. I guess you mean you want the values to be sorted.
    my @sorted = sort {$a -> [1] <=> $b -> [1]} values %hash;
    Abigail
Re: Sorting Hash
by hotshot (Prior) on Aug 08, 2002 at 11:19 UTC
    you can try
    @keys = sort { $hash{$a} cmp $hash{$b} } keys %hash; # and by value
    this question is quite common, use the search engine first,next time.

    Thanks.

    Hotshot
Re: Sorting Hash
by danboo (Beadle) on Aug 08, 2002 at 14:17 UTC
    Since you're hash values are array refs, you need to access them as such:
    my @sorted_keys = sort { $hash{$a}[1] <=> $hash{$b}[1] } keys %hash;
    - danboo