对嵌套散列的散列键进行排序 [英] Sort hash keys of nested hash

查看:120
本文介绍了对嵌套散列的散列键进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在perl中,我有一个如下所示的哈希:

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

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

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

如何通过键 a的值来排序此散列的键。例如,按键 a 的值按数字升序对上述散列进行排序将给出:key1,key3,key2。

解决方案

perl没有排序哈希的概念,您必须在foreach循环中排序您的键:

 #!/ 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$ _\\\
foreach sort {$ hash {$ a} - > {a}< => $ hash {$ b} - > {a}}键%hash;

或者,您可以将 sort的结果在数组中循环。


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.

解决方案

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.

这篇关于对嵌套散列的散列键进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆