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

Hi,

I've had a search for this and if I've read the answer anywhere I haven't recognised it as such.

I want to sort a hash by its value...but its value is an array. I want to use the first element in that array for sorting.

i.e. to sort a hash by $hash{$key}[0]

It's possible that this is a stupid thing to do and that's why I can't find anything on it.

Anyway, thanks for reading.

MorayJ

Replies are listed 'Best First'.
Re: Sorting an hash of an array by a value in the array
by BrowserUk (Patriarch) on Jan 12, 2012 at 15:17 UTC

    You cannot actually "sort a hash" per se, but you can create an array of the keys in the required order and then use that to iterate the hash:

    %h = ( a=>[3,1..4], b=>[2,1..4], c=>[0..4] );; @sortedKeys = sort{ $h{ $a }[0] <=> $h{ $b }[0] } keys %h;; print "$_ : @{ $h{ $_ } }" for @sortedKeys;; c : 0 1 2 3 4 b : 2 1 2 3 4 a : 3 1 2 3 4

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

    The start of some sanity?

      Great - thanks. Just what I was looking for and relatively straightforward, though I still have to get used to a lot of this hash syntax!

      Cheers again

      MorayJ

A reply falls below the community's threshold of quality. You may see it by logging in.