in reply to sorting hashes by value

Do you want to sort the values or sort the keys by their values? I suspect the latter. Here's how to get a list of words sorted by value:

@words = sort { $word_list{$a} <=> $word_list{$b} } keys %word_list;

This works because keys() returns a list of keys for the %word_list hash. Then the sort block compares these keys by looking up their value in %word_list. The return from sort is the list of keys sorted by their values.

If you really wanted a list of sorted values, that's just:

@values = sort values %word_list;

-sam

Replies are listed 'Best First'.
Re: Re: sorting hashes by value
by imlou (Sexton) on Nov 08, 2002 at 21:27 UTC
    Thanks! so when its sorted into @words does it keep the word and the value? So in order for me to print it do I
    for $i (0.. $#words_list){ for $words (keys %{$words[$i]}){ print "word $i = $words\n"; } }
    ??
      No, that won't work. If you need to keep the values along with the keys you can build it into the sort:

      @pairs = sort { $a->[1] <=> $b->[1] } map { [ $_ => $word_list{$_} ] } keys %word_list; print "word $_->[0] = $_->[1]\n" for @pairs;

      This works by building up a list of two-element arrays using map. The first element is the key and the second element is the value. Then sort is used to sort them by the second element. The return value is a list of two-element arrays, sorted by their second element.

      You might recognize this as the tail of a Schwartzian Transform.

      -sam

        Or it may be easier to understand as this:
        foreach my $sortedkey (sort {$hashname{"$a"} <=> $hashname{"$b"} } key +s %hashname) { printf "Value: %d Key: %s", %hashname{"$sortedkey"}, $sortedkey; }


        -Waswas
        Thanks Sam. Now I getting a better understanding of how map and sort works!
      While samtregar is right in his method for keeping the keys and values together, you probably don't need to go to that trouble. Why not just do something like this:
      @words = sort { $word_list{$a} <=> $word_list{$b} } keys %word_list; foreach $word (@words) { print "word $word = $word_list{$word}\n"; }
      @words is already a sorted list of the keys in %word_list. Of course, this assumes that nobody is doing pesky things like adding to %word_list between the time you sorted it and the time you decided to print it.