[英]Search in an array of hashes by the hash key and its sorting in Perl
[英]Sorting an array of hashes, based on the value of a particular key within each hash in perl
我做了一些搜索,并努力找到这个答案。
说我有像这样的哈希数组..
my @AoH = (
{ 'ip_type' => 1,
'ip_ref' => 0001,
'ip_address' => '192.168.0.1',
'ip_priority' => '100'
},
{ 'ip_type' => 1,
'ip_ref' => 0002,
'ip_address' => '192.168.0.2',
'ip_priority' => '1'
}
);
在上下文中,这些是多个IP地址,我打算在其中进行负载平衡。 'ip_priority'值指示哪个是第一个,然后是第二个在pirority中。 主要和备份,基本上。
但是,我想根据哈希中的ip优先级值以数字方式对数组元素(也称为哈希)进行排序。
所以,最好是上面的AoH ......
my @AoH = (
{ 'ip_type' => 1,
'ip_ref' => 0002,
'ip_address' => '192.168.0.2',
'ip_priority' => '1'
},
{ 'ip_type' => 1,
'ip_ref' => 0001,
'ip_address' => '192.168.0.1',
'ip_priority' => '100'
}
);
所以$AoH[0]->{ip_priority}
现在$AoH[0]->{ip_priority}
1和$AoH[1]->{ip_priority}
包含100。
如何执行排序以实现上面的第二个示例? 我很难找到一个可行的例子!
您可以使用:
my @sorted = sort {$a->{ip_priority} <=> $b->{ip_priority}} @AoH;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.