Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!wuarchive!uwm.edu!bionet!agate!ucbvax!iwarp.intel.com!news From: merlyn@iwarp.intel.com (Randal L. Schwartz) Newsgroups: comp.lang.perl Subject: Re: Sorting an associative array by value? Message-ID: <1991Apr5.195946.5019@iwarp.intel.com> Date: 5 Apr 91 19:59:46 GMT References: <1991Apr5.183701.21325@javelin.sim.es.com> Sender: news@iwarp.intel.com Reply-To: merlyn@iwarp.intel.com (Randal L. Schwartz) Organization: Stonehenge; netaccess via Intel, Beaverton, Oregon, USA Lines: 36 In-Reply-To: pashdown@javelin.sim.es.com (Pete Ashdown) In article <1991Apr5.183701.21325@javelin.sim.es.com>, pashdown@javelin (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)) { foreach $word (sort bywordcount keys(%wordcount)) { | printf "%20s %d\n", $word, $wordcount{$word}; | } sub bywordcount { $wordcount{$a} <=> $wordcount{$b}; # use spaceship operator for numeric } See the sort operator description on page 180 of The Book. @a=('hacker,',Just,Perl,another);@a=grep($_=splice(@a,$_,1),1,2,1,0);print"@a" -- /=Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ==========\ | on contract to Intel's iWarp project, Beaverton, Oregon, USA, Sol III | | merlyn@iwarp.intel.com ...!any-MX-mailer-like-uunet!iwarp.intel.com!merlyn | \=Cute Quote: "Intel: putting the 'backward' in 'backward compatible'..."====/