Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
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" }

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

    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?
talexb just used & intentionally in a script and feels pretty good about it.

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (9)
As of 2016-12-07 18:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:













    Results (131 votes). Check out past polls.