【发布时间】:2013-12-04 21:52:16
【问题描述】:
我目前正在尝试按多维哈希中的值进行排序,但我有点难过。
我在单个级别上完成了如下操作:
my %exampleHash = ();
$exampleHash{1}{value} = 10;
$exampleHash{2}{value} = 30;
$exampleHash{3}{value} = 0;
$exampleHash{4}{value} = 20;
foreach my $key ( reverse sort {$exampleHash{$a}{value} <=> $exampleHash{$b}{value}} keys %exampleHash )
{
printf( "%s => %d\n", $key, $exampleHash{$key}{value} );
}
这会产生以下输出,按预期按值排序:
2 => 30
4 => 20
1 => 10
3 => 0
然后我尝试了以下方法来做同样的事情,但使用了一个额外的密钥:
my %exampleHashTwo = ();
$exampleHashTwo{1}{"One"}{value} = 10;
$exampleHashTwo{2}{"Two"}{value} = 30;
$exampleHashTwo{3}{"Three"}{value} = 0;
$exampleHashTwo{4}{"Four"}{value} = 20;
foreach my $intKey ( keys %exampleHashTwo )
{
foreach my $stringKey ( reverse sort {$exampleHashTwo{$intKey}{$a}{value} <=> $exampleHashTwo{$intKey}{$b}{value}} keys %{$exampleHashTwo{$intKey}} )
{
printf( "{%d} - {%5s} => %d\n", $intKey, $stringKey, $exampleHashTwo{$intKey}{$stringKey}{value} );
}
}
但是,这似乎是按字母顺序对字符串键进行排序。所以我假设我在正确的路线上,但也许我放错了地方?
{4} - { Four} => 20
{1} - { One} => 10
{3} - {Three} => 0
{2} - { Two} => 30
有什么想法吗?
【问题讨论】:
标签: perl sorting hash multidimensional-array