-1

I have an hash which looks like this when I use dumper:

{      
 hello => {   
    pqr => {   
     a => 455,
     b => 52,
     c => "hello"
    },
    lmn => {
     a => 3,
     b => 39,
     c => "hi"
    }
 },
 hi => {
    suv => {
     a => 21,
     b => 36,
     c => "well"
    },
    xyz => {
     a => 32,
     b => 56,
     c => "done"
    }
 }
}

I would like to sort based on the value of "b".

Output should be like:

hello.lmn.b = 39 hello.pqr.b = 52

hi.suv.b = 36 hi.xyz.b = 56

jira
  • 3,890
  • 3
  • 22
  • 32
Sai Kiran
  • 145
  • 1
  • 2
  • 5

1 Answers1

2

You should use sort for sorting lists. In this case the hash is nested so it is iterated at first level keys and then sorted with second level keys according to the values the b contains at third level.

for my $k1 (keys %hash) {
    for my $k2 (sort {$hash{$k1}{$a}{'b'} <=> $hash{$k1}{$b}{'b'}} keys %{$hash{$k1}}) {
        print "$k1.$k2.b = ",$hash{$k1}{$k2}{'b'}, " ";
    }
    print "\n";
}
Arunesh Singh
  • 3,489
  • 18
  • 26