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