How can I sort a Perl array of array of hashes?

By : ksskr
Source: Stackoverflow.com
Question!
@aoaoh;

$aoaoh[0][0]{21} = 31;
$aoaoh[0][0]{22} = 31;
$aoaoh[0][0]{23} = 17;

for $k (0 .. $#aoaoh) {
    for $i(0.. $#aoaoh) {
        for $val (keys %{$aoaoh[$i][$k]}) {
            print "$val=$aoaoh[$i][$k]{$val}\n";
        }
    }
}

The output is:

    22=31
    21=31
    23=17

but i expect it to be

    21=31
    22=31
    23=17

Please tell me where is this wrong.

Also how do I sort the values so that i get the output as

    23=17 
    22=31
    21=31 (if 2 keys have same value then key with higher value come first)
By : ksskr


Answers

It sounds like you are expecting hashes to return their keys and values in the order defined, where there is no such guarantee in perl.

You can either implement a more complex data structure that handles some of the ordering for you, or put some more sorting logic in your display (instead of just looping), or load up a module to support ordered hashes, such as Tie::Hash::Indexed.

I would expect the Tie::Hash::Indexed implementation to look like so:

my @aoaoh;

use Tie::Hash::Indexed;
tie my %hash, 'Tie::Hash::Indexed';
$aoaoh[0][0] = \%hash;

$aoaoh[0][0]{21} = 31;
$aoaoh[0][0]{22} = 31;
$aoaoh[0][0]{23} = 17;

for $k (0 .. $#aoaoh) {
    for $i(0.. $#aoaoh) {
        for $val (keys %{$aoaoh[$i][$k]}) {
            print "$val=$aoaoh[$i][$k]{$val}\n";
        }
    }
}
By : kbenson


I answered on of the other two exact same questions by this user, but it looks like this one is going to win so I'm answering here too.

From perlfaq4's answer to How do I sort an array by anything?


Supply a comparison function to sort() (described in sort in perlfunc):

@list = sort { $a 


Answer for Q1 will be:

print "${$aoaoh[0][0]}{$_}=$_\n" for sort keys %{$aoaoh[0][0]};

what could be written as:

for (sort keys %{$aoaoh[0][0]}) {
    print "${$aoaoh[0][0]}{$_}=$_\n"
}

And the answer for Q2:

print "$_-
By : czubatka


This video can help you solving your question :)
By: admin