How can I keep a hash sorted?

Posted by srk on Stack Overflow See other posts from Stack Overflow or by srk
Published on 2010-03-26T00:05:33Z Indexed on 2010/03/26 1:33 UTC
Read the original article Hit count: 410

Filed under:
|
|
|
    use strict; 
    use warnings; 
    my @aoh =( 
     { 
        3 => 15, 
        4 => 8, 
        5 => 9, 
     }, 
     { 
        3 => 11, 
        4 => 25, 
        5 => 6, 
     }, 
    { 
        3 => 5, 
        4 => 18, 
        5 => 5, 
    }, 
    { 
        0 => 16, 
        1 => 11, 
        2 => 7, 
    }, 
    { 
        0 => 21, 
        1 => 13, 
        2 => 31, 
     }, 
    { 
        0 => 11, 
        1 => 14, 
        2 => 31, 
    }, 
    ); 
    #declaring a new array to store the sorted hashes 
    my @new; 
    print "\n-------------expected output------------\n"; 
    foreach my $href (@aoh) 
    { 
    #i want a new array of hashes where the hashes are sorted 
    my %newhash; 
    my @sorted_keys = sort {$href->{$b} <=> $href->{$a} || $b <=> $a} keys %$href; 
       foreach my $key (@sorted_keys) 
       { 
             print "$key => $href->{$key}\n"; 
           $newhash{$key} = $href->{$key}; 
     } 
    print "\n"; 
    push(@new,\%newhash); 
    } 
    print "-----------output i am getting---------------\n"; 
    foreach my $ref(@new) 
    { 
     my @skeys = skeys %$ref; 
       foreach my $key (@skeys) 
       { 
           print "$key => $ref->{$key}\n" 
       } 
       print "\n"; 
    }

The output of the program :

    -------------expected output------------ 
    3 => 15 
    5 => 9 
    4 => 8 

    4 => 25 
    3 => 11 
    5 => 6 

    4 => 18 
    5 => 5 
    3 => 5 

    0 => 16 
    1 => 11 
    2 => 7 

    2 => 31 
    0 => 21 
    1 => 13 

    2 => 31 
    1 => 14 
    0 => 11 



        -----------output i am getting---------------
    4 => 8
    3 => 15
    5 => 9

    4 => 25
    3 => 11
    5 => 6

    4 => 18
    3 => 5
    5 => 5

    1 => 11
    0 => 16
    2 => 7

    1 => 13
    0 => 21
    2 => 31

    1 => 14
    0 => 11
    2 => 31

Please tell me what am i doing wrong in storing the hashes into a new array.. how do i achieve what i want.. ? Thanks in advance...

© Stack Overflow or respective owner

Related posts about perl

Related posts about array