Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: how to sort hash of array by value

by dwm042 (Priest)
on Oct 02, 2007 at 14:44 UTC ( [id://642120]=note: print w/replies, xml ) Need Help??


in reply to how to sort hash of array by value

One of the problems with providing a data set that is apparently already sorted is that it's hard to prove that the solution can indeed sort (unless you change the actual sort in use):

#!/usr/bin/perl use warnings; use strict; my %colorhash = ( CCgray => ["0","0","0"], CCwhite => ["1","0","0"], CCgrey => ["0","2","0"], CCBlue => ["0","0","3"], ); print "Original order of data:\n\n"; foreach my $colorname (keys %colorhash) { printf "For key %-7s : ",$colorname; for my $i (0.. $#{ $colorhash{$colorname} } ){ print "element[", $i,"] = $colorhash{$colorname}[$i] "; } print "\n"; } print "\n\n"; my @light2dark = sort lightsort (keys %colorhash); my @dark2light = sort darksort (keys %colorhash); print "Order, dark is ",join(',',@dark2light), ".\n"; print "Order, light is ",join(',',@light2dark), ".\n"; sub darksort { $colorhash{$b}[0] <=> $colorhash{$a}[0] or $colorhash{$b}[1] <=> $colorhash{$a}[1] or $colorhash{$b}[2] <=> $colorhash{$a}[2] } sub lightsort { $colorhash{$a}[0] <=> $colorhash{$b}[0] or $colorhash{$a}[1] <=> $colorhash{$b}[1] or $colorhash{$a}[2] <=> $colorhash{$b}[2] }
And the results are:

C:\Code>perl color-sort.pl Original order of data: For key CCBlue : element[0] = 0 element[1] = 0 element[2] = 3 For key CCgray : element[0] = 0 element[1] = 0 element[2] = 0 For key CCgrey : element[0] = 0 element[1] = 2 element[2] = 0 For key CCwhite : element[0] = 1 element[1] = 0 element[2] = 0 Order, dark is CCwhite,CCgrey,CCBlue,CCgray. Order, light is CCgray,CCBlue,CCgrey,CCwhite.
Update: cleaner logic

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://642120]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (5)
As of 2024-04-26 07:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found