Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Sort hash ref of Hash of Hashes

by kalyanrajsista (Scribe)
on Jul 06, 2010 at 10:11 UTC ( #848176=perlquestion: print w/replies, xml ) Need Help??
kalyanrajsista has asked for the wisdom of the Perl Monks concerning the following question:


I'm trying to sort hash of hashes with the following code but not achieving what I want .. Here is what I've tried. Can I get one more hash reference with all sorted values...

use strict; my $DATA = { '315' => { 'vrec' => 'ABCDE', 'vpay' => 'AGOUT' }, '319' => { 'vrec' => 'TEST2', 'vpay' => 'AGOUT' }, '321' => { 'vrec' => 'LIMCA', 'vpay' => 'AGOUT' }, '323' => { 'vrec' => 'ALBVF', 'vpay' => 'AGOUT' }, '325' => { 'vrec' => 'TEST1', 'vpay' => 'AGOUT' }, '313' => { 'vrec' => 'PQRST', 'vpay' => 'AGOUT' } }; foreach (sort { $DATA->{$a}->{'vrec'} <=> $DATA->{$b}->{'vrec'} } keys +(%{$DATA}) ) { print "key: $_ value: $DATA->{$_}\n" }

Replies are listed 'Best First'.
Re: Sort hash ref of Hash of Hashes
by BioLion (Curate) on Jul 06, 2010 at 10:34 UTC

    You are comparing string values 'PQRST' etc... but using the numerical sort (spaceship '<=>') operator. You should be using cmp. See sort for more info.

    Just a something something...
      ... and use warnings; would have warned you that Argument "PQRST" isn't numeric in numeric comparison (<=>) at ....

      So, always use warnings;. (Documented in perllexwarn).

Re: Sort hash ref of Hash of Hashes
by roboticus (Chancellor) on Jul 06, 2010 at 10:37 UTC


    You're very close: You need to use cmp instead of <=> to compare strings. Also, I changed your print statement to the following to make the result easier to check:

    print "$_ ==> { vrec=$DATA->{$_}{vrec}, vpay=$DATA->{$_}{vpay} }\n +";


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://848176]
Approved by Corion
[Discipulus]: more: just one thread in the last ~5 years
[Discipulus]: but Dumas is waiting for me in the bed.. luckly as book author.. see you!
[ELISHEVA]: Sleep well!
[ELISHEVA]: Or read well
[Discipulus]: thanks, best dreams to you all

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (9)
As of 2017-05-28 20:47 GMT
Find Nodes?
    Voting Booth?