Is there some perl "magic" to iterate through a hash sorted by the values but get the key in the iteration?
Sort by X and get X is easy (keys, values) - as well as sort by key and get the value.
Thanks!
Is there some perl "magic" to iterate through a hash sorted by the values but get the key in the iteration?
Sort by X and get X is easy (keys, values) - as well as sort by key and get the value.
Thanks!
my %hash = ( one => 'a', two => 'b', three => 'c', four => 'd' );
for my $k ( sort { $hash{$a} cmp $hash{$b} } keys %hash ) {
print "$k: $hash{$k}\n";
}
__END__
one: a
two: b
three: c
four: d
Please remember in future to give an example of your data, the required result, and the code that you've written together with an account of what is wrong with it.
As it stands your question is very vague, and I have had to make several assumptions which may or may not be wrong
It isn't "magical"; you simply have to write the appropriate sort
block
This will sort the keys of %hash
in ascending lexical order of their corresponding values
my @sorted_keys = sort { $hash{$a} cmp $hash{$b} } keys %hash;
You may also make use of List::UtilsBy
, like this. It may be significantly faster than the simple sort
technique, depending on your data
use List::UtilsBy 'sort_by';
my @sorted_keys = sort_by { $hash{$_} } keys %hash;