Sort hash keys of nested hash

丶灬走出姿态 提交于 2019-12-22 23:41:53

问题


In perl, I have a hash that looks like the following:

   $hash{key1}->{a} = 1;
   $hash{key1}->{b} = 3;

   $hash{key2}->{a} = 4;
   $hash{key2}->{b} = 7;

   $hash{key3}->{a} = 2;
   $hash{key3}->{b} = 5;

How can I sort the keys of this hash by the value of key a. For instance, sorting the above hash in numerical ascending order by the values of key a would give: key1,key3,key2.


回答1:


perl has no notion of a sorted hash, you'll have to "sort" your keys in a foreach loop:

#!/usr/bin/perl -W
use strict;

my %hash = ();

$hash{key1}->{a} = 1;
$hash{key1}->{b} = 3;

$hash{key2}->{a} = 4;
$hash{key2}->{b} = 7;

$hash{key3}->{a} = 2;
$hash{key3}->{b} = 5;

print "$_\n" foreach sort {$hash{$a}->{a} <=> $hash{$b}->{a}} keys %hash;

Alternatively, you can put the result of the sort in an array and loop on this array.



来源:https://stackoverflow.com/questions/8782038/sort-hash-keys-of-nested-hash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!