I believe this is how you would normally sort a hash by value:
foreach my $key (sort { $hash{$a} <=> $hash{$b} } (keys %hash) ) {
print "$key=>$hash{$key}";
}
This would print out the values smallest to largest.
Now, what if I have a hash like this:
$hash{$somekey}{$somekey2}{$thirdkey}
How could I sort by values and get all the keys as well?
If you want to access a Hash in a sorted manner by key, you need to use an Array as an indexing mechanism as is shown above. This works by using the Emmuerator#sort_by method that is mixed into the Array of keys. #sort_by looks at the value my_hash[key] returns to determine the sorting order.
The hash sort is a general purpose non-comparison based sorting algorithm by hashing, which has some interesting features not found in conventional sorting algorithms. The hash sort asymptotically outperforms the fastest traditional sorting algorithm, the quick sort.
For example we can sort the hash first by the Position value, and among the entries with the same Position value we can sort by the value of the Max field. In order to do this we will use the following expression: my @maxed = sort { $data->{$a}{Position} <=> $data->{$b}{Position}
Sorting Hashes in Ruby To sort a hash in Ruby without using custom algorithms, we will use two sorting methods: the sort and sort_by. Using the built-in methods, we can sort the values in a hash by various parameters.
I would just create a new hash:
my %new;
for my $k1 (keys %hash) {
for my $k2 (keys %{$hash{$k1}}) {
for my $k3 (keys %{$hash{$k1}{$k2}}) {
$new{$k1,$k2,$k3} = $hash{$k1}{$k2}{$k3};
}
}
}
my @ordered = sort { $new{$a} <=> $new{$b} } keys %new;
for my $k (@ordered) {
my @keys = split($;, $k);
print "key: @k - value: $new{$k}\n";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With