in reply to Want to sort hashes by values, anyone?

Uh...
my @sorted_keys_by_value = sort { $unsorted_hash{$a} cmp $unsorted_hash{$b} } keys %unsorted_hash;
And you probably want to use 'cmp' instead of '<=>'. '<=>' is for numerical comparison, 'cmp' is for strings. See perlop.

Replies are listed 'Best First'.
Re: Re: Want to sort hashes by values, anyone?
by Doraemon (Beadle) on May 11, 2004 at 15:30 UTC
    just ignore for my purpose (i use numbers). cmp not produce what i expect.
    '9' will be greater than '11'
    This not what i want. Anyway, i realize cmp still more preferrable if multi purposes
      Anyway, i realize cmp still more preferrable if multi purposes

      No, you cannot make general statements like that and be right. Basically, what we're trying to say is you are reinventing the wheel, and poorly at that. Use the tools that have been made for you so you can build what you're being paid to build. (I doubt your employer wants to pay you for sorting hashes by value ...)

      ------
      We are the carpenters and bricklayers of the Information Age.

      Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

      I shouldn't have to say this, but any code, unless otherwise stated, is untested

      So you want to sort numerically, that's okay, but then neither a simple cmp nor <=> will work. <=> would work if your values were suffixed by non-numeric characters, but not prefixed the way you have them. In that case my answer would probably be a Schwartzian Transform, but would vary depending on how generic I want my answer to be, and what I know of the data (e.g. does it always start with a 'v'? do I just want to extract the first number out of it and sort by that? should I consider the character portion in the sort? etc.).

      And your answer does not work. If it does seem to work in some version of perl for some set of data, then it is a matter of luck.

Re: Re: Want to sort hashes by values, anyone?
by Doraemon (Beadle) on May 12, 2004 at 01:35 UTC
    I never invent wheels, honest!
    Just kidding. I realize that, because i'm just a Perl's 'magot'. But i'm still insist on reinventing, since i enjoy to do it :) (that's not in my task's list, though) Anyway, i made the statement, since i've seen most scalar type can be treated as string, and cmp is suitable for comparison in general. It is safer, although not efficient (need to do conversion).