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

Re: sort hash of array by value

by snopal (Pilgrim)
on Oct 01, 2007 at 23:16 UTC ( #642020=note: print w/replies, xml ) Need Help??


in reply to how to sort hash of array by value

I'm not sure if this is homework, but you certainly won't get that code to work.

#!/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"]); foreach my $colorname (keys %colorhash) { for my $i (0.. $#{ $colorhash{$colorname} } ) { print "$i = $colorhash{$colorname}[$i] "; } print "\n"; } my @light2dark = sort numsort (keys %colorhash); sub numsort { $colorhash{$a}[0] <=> $colorhash{$b}[0] or $colorhash{$a}[1] <=> $colorhash{$b}[1] or $colorhash{$a}[2] <=> $colorhash{$b}[2] }

Replies are listed 'Best First'.
Re^2: sort hash of array by value
by snopal (Pilgrim) on Oct 02, 2007 at 00:00 UTC

    Responding to my own post.

    First rule:

    use warnings;
    use strict;

    That's the annoying but seemingly impossible to avoid mantra of a good perl developer. Exclude them at your own risk, and only when you know why you are doing so. You really needed to find out where the code just would not work.

    As previously remarked, your value assignment strategy does not do what you think. Since '=>' is just a sophisticated comma, your hash assignment is interpreted as:

    %colorhash = (CCgray => "0", "0" => "0", CCwhite => "1", "0" => "0", etc.

    I think you can see where this is going. Anonymous arrays are constructed within brackets.

    As mentioned before, the quotes around clearly numeric values are unnecessary.

    Next, for some reason, your example has:

    $colorhash{$colorname}$i

    Obviously, the array brackets are missing.

    You should also research the usage of 'sort'. You defined a sort evaluation call, but didn't call sort to use it.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (9)
As of 2020-10-29 14:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (271 votes). Check out past polls.

    Notices?