Beefy Boxes and Bandwidth Generously Provided by pair Networks RobOMonk
go ahead... be a heretic
 
PerlMonks  

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:

Monks

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" }

Comment on Sort hash ref of Hash of Hashes
Download Code
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 (Canon) on Jul 06, 2010 at 10:37 UTC

    kalyanrajsista:

    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 +";

    ...roboticus

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (12)
As of 2014-04-24 12:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (565 votes), past polls