Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!swrinde!cs.utexas.edu!uunet!orca!orca!rkrebs From: rkrebs@fantasy.dsd.es.com (Randall Krebs) Newsgroups: comp.lang.perl Subject: Re: Sorting an associative array by value? Message-ID: Date: 5 Apr 91 17:47:50 GMT References: <1991Apr5.183701.21325@javelin.sim.es.com> Sender: usenet@dsd.es.com Organization: /usr9/appl/rkrebs/.organization Lines: 39 In-Reply-To: pashdown@javelin.sim.es.com's message of Fri, 5 Apr 91 18:37:01 GMT Nntp-Posting-Host: 130.187.85.135 In article <1991Apr5.183701.21325@javelin.sim.es.com> pashdown@javelin.sim.es.com (Pete Ashdown) writes: How do I go about sorting an associative array, not by the string, but by the associated value? For example, how would I change following 'word count' program to sort by occurance rather than alphabetically? (From the Nutshell Book) while (<>) { s/-\n//g; tr/A-Z/a-z/; @words = split (/\W*\s+\W*/, $_); foreach $word (@words) { $wordcount {$word}++; } } foreach $word (sort keys(%wordcount)) { printf "%20s %d\n", $word, $wordcount{$word}; } Try: sub freqsort { $wordcount{$a} <=> $wordcount{$b}; } foreach $word (sort(freqsort keys(%wordcount))) { printf "%20s %d\n", $word, $wordcount{$word}; } randall. -- Randall S. Krebs | "If you don't drink, don't drive. (rkrebs@dsd.es.com) | And if you don't read the man Evans & Sutherland Computer Corporation | page, don't run the program." Salt Lake City, Utah (Where?) | - Sister Admin