in reply to How to sort HASH?

I had a similar project awhile back. I had pulled ip addresses from my apache access log and wanted to see how many times a certain ip hit our web site. Basically I used the ip addresses as the hash keys and the value was incremented for each instance. Everyone told me I could not sort by the values (sounds like you want to do the same thing here). I did notice in the perl cookbook something that worked in sorting the values... sorta :-) Long story shore, I was able to sort / print the values in order. Worked great! Here is the sorting of the hash I used. Hopefully this will help:
# This section will count the number of times we see an ip address open ACCESSLISTIPS, "access_log_ips" or die "The file could not be opened ($!)"; chomp(@ips = <ACCESSLISTIPS>); foreach $ip (@ips) { $count{$ip} += 1; } # This routine will sort the values of a hash then print them out for +us. # foreach $ip (sort { $count{$a} cmp $count{$b} } keys %count) { print "$ip was seen $count{$ip} times.\n"; }

Replies are listed 'Best First'.
Re: Re: How to sort HASH?
by Limbic~Region (Chancellor) on Apr 05, 2004 at 18:19 UTC
    u235sentinel,
    Everyone told me I could not sort by the values

    Since this is your first write-up on this site, I will assume you mean everyone somewhere else told you this. I believe this may have been a misunderstanding by you, them or likely both. You can get the keys of the hash returned to you in sorted order by any abitrary sorting method you want. The hash itself is still stored internally in its own order. This means you have to repeat the sort routine each time you want to view the hash sorted. There are modules that do the sorting for you under the covers given the appearance of a sorted hash.

    I was able to sort / print the values in order

    I hope you did not use the code you are showing here. You are using cmp when you should be using <=>. The difference is textual comparison versus numerical. Do you really want 2 coming after 10?

    Welcome to the Monastery! - L~R
      oops ..

      Yes I did use this code and now I see I was a 'little' too quick to push it out. But then again, I'm a noob still. Thx for the tip. I made the change and tested it against my access list. So cmp does a text comparison? That part was unclear. :-)

      I will assume you mean everyone somewhere else told you this

      Yup. It was in speaking with my co-workers. Seems I was lead astray :-)

      Thx again!