如何根据键值对多级 perl 哈希进行排序(和打印)?
%hash = (
a => { k1 => 51, k2 => 52, k3 => 53 },
b => { k1 => 61, k2 => 62, k3 => 63 },
c => { k1 => 71, k2 => 72, k3 => 73 },
)
例如,根据k2
?的值对上述散列进行数字排序 所以它应该打印:
52,62,72
我想知道如何使用
sort { $hash{$b} <=> $hash{$a} } keys %hash`
编辑
如果我有另一个哈希
my %property = ( a => 7, b => 6, c => 5 )
我可以根据
使用%hash
的数值 进行排序吗$hash{key}{k2} * $property{key}
#!/usr/bin/perl
use strict;
use warnings;
my %hash = (
a => { k1 => 51, k2 => 52, k3 => 53 },
b => { k1 => 61, k2 => 62, k3 => 63 },
c => { k1 => 71, k2 => 72, k3 => 73 },
);
my %property = ( a => 7, b => 6, c => 5 );
foreach (sort { ($hash{$a}{'k2'}*$property{$a}) <=>
($hash{$b}{'k2'}*$property{$b}) } keys %hash)
{
printf("[%d][%d][%d]\n",
$hash{$_}{'k2'},$property{$_},$hash{$_}{'k2'}*$property{$_});
}
结果应该是
72,52,62 as products are (360(72*5),364(52*7),372(62*6))