Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Sorting of hash by value

by perlCrazy (Monk)
on Jan 12, 2009 at 06:10 UTC ( #735612=perlquestion: print w/replies, xml ) Need Help??
perlCrazy has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,
I have hash structure like this :
%devLst = ("dev1" => 2001,"dev2" => 1791, "dev3" => 32000,"dev4" => 1791, "dev5" => 32000,"dev6" => 1791, "dev7" => 32000 );
where dev1 = device name and 2001 = size of device
Want to make one array where all device name (dev1...devn). Should be in ascending order by size.
My final array should look like this:
ex: my @resArr = (dev2,dev4,dev6,dev1,dev3,dev5,dev7); Any help will be appriciated.

Replies are listed 'Best First'.
Re: Sorting of hash by value
by ikegami (Pope) on Jan 12, 2009 at 06:25 UTC
    my @resArr = sort { $devLst{$a} <=> $devLst{$b} } keys %devLst;
Re: Sorting of hash by value
by moritz (Cardinal) on Jan 12, 2009 at 06:23 UTC
    See perlfaq4, "How do I sort a hash (optionally by value instead of key)?"
Re: Sorting of hash by value
by BrowserUk (Pope) on Jan 12, 2009 at 06:26 UTC
    my @resArr = sort{ $devLst{ $a } <=> $devLst{ $b } } sort keys %devLst;;

    Update: That said, if your keys are really Dev1 ... DevN, then you'd same memory and avoid one level of sort by storing your data in an array to start with:

    @devLst = (undef, 2001, 1791, 32000, 1791, 32000, 1791, 32000 );; print "dev$_" for sort{ $devLst[ $a ] <=> $devLst[ $b ] } 1 .. $#devLs +t; dev2 dev4 dev6 dev1 dev3 dev5 dev7

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Sorting of hash by value
by wfsp (Abbot) on Jan 12, 2009 at 06:48 UTC
    my @name_by_size = sort { $devLst{$a} <=> $devLst{$b} || $a cmp $b } keys %devLst;
      Thanks all for prompt reply.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://735612]
Approved by planetscape
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2017-09-26 05:50 GMT
Find Nodes?
    Voting Booth?
    During the recent solar eclipse, I:

    Results (292 votes). Check out past polls.