My data structure is
my %hash = (
firstkey => {
secondkey => {
2 => ['9','2'],
1 => ['3','4'],
3 => ['8','2']
}
}
);
print Dumper \%hash;
I want to sort the hash by the thirdly key. i.e. 1
, 2
and 3
in this case
and then compare the second element (index[1]
) in the array. If they are the same, and then print it out.
Expected Sorted Hash:
my %hash = (
firstkey => {
secondkey => {
1 => ['3','4'],
2 => ['9','2'],
3 => ['8','2']
}
}
);
print Dumper \%hash;
After sort the hash, we compare the index[1]
of the 1st array[3,4]
with the 2nd array[9,2]
.
4
is not equal to 2
, so we are not going to print anything.
Then, we compare the index[1]
of the 2nd array[9,2]
with the 3rd array[4,2]
.
2
is equal to 2
, then we are going to print all the content of it
firstkey, secondkey, 3, [8,2]
we only need to compare the adjacent array.
I read a lot of solutions about sorting the hash, but I couldn't find one solution that really reorders it Is it any way to reorder the hash by the key and construct a hash with the new order in Perl? Or we can only sort the hash by using the for loop and compare it in the for loop?
sort
on the list of hash's keys with any criteria you wish. Then you have an ordered list of keys to iterate though so you can use your hash in a "sorted manner." See this post for sorting a similar hash, or this post for a bit more involved sort with some comments. There is a lot more out there. - zdim