Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

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
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2018-02-23 03:47 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (300 votes). Check out past polls.