How to sort perl hash on values and order the keys correspondingly (in two arrays maybe)?

前端 未结 4 1632
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 15:03

In Perl, I want to sort the keys of a hash by value, numerically:

{
  five => 5
  ten => 10
  one => 1
  four => 4
}

producing

4条回答
  •  隐瞒了意图╮
    2020-12-08 15:30

    First sort the keys by the associated value. Then get the values (e.g. by using a hash slice).

    my @keys = sort { $h{$a} <=> $h{$b} } keys(%h);
    my @vals = @h{@keys};
    

    Or if you have a hash reference.

    my @keys = sort { $h->{$a} <=> $h->{$b} } keys(%$h);
    my @vals = @{$h}{@keys};
    

提交回复
热议问题