我有一个嵌套哈希如下
$hash{$key1}{$key2}{$key3} = value;
my %hash = (
name1 => {
a => { line => 4, page => 112 },
b => { line => 6, page => 134 },
c => { line => 1, page => 112 }
},
name2 => {
a => { line => 43, page => 112 },
b => { line => 12, page => 134 },
c => { line => 55, page => 112 }
}
)
我想根据key2
中的升序值对line
进行排序。即name1
应将key2
排列为c
,a
,b
和name2
应该包含b
,{{ 1}},a
。
我知道哈希总是给出随机对,但有没有办法对值进行系统排列以获得排序键?
答案 0 :(得分:1)
不保证散列键以任何特定顺序存储,但您可以创建专用索引数组(在您的情况下为数组引用的散列),这将存储按需排序的键:
my %sorted;
foreach my $key1 (keys %hash) {
$sorted{$key1} = [
sort {
$hash{$key1}{$a}{"line"}
<=>
$hash{$key1}{$b}{"line"}
} keys $hash{$key1}
];
}
然后你可以用这种方式使用@{$sorted{$key1}}
索引数组,例如:
foreach my $key1 (keys %hash) {
foreach my $key2 (@{$sorted{$key1}}) {
print "$key1.$key2: "
."line: $hash{$key1}{$key2}{'line'}, "
."page: $hash{$key1}{$key2}{'page'}\n";
}
}
输出:
name2.b: line: 12, page: 134
name2.a: line: 43, page: 112
name2.c: line: 55, page: 112
name1.c: line: 1, page: 112
name1.a: line: 4, page: 112
name1.b: line: 6, page: 134
答案 1 :(得分:1)
只有数组可以按特定顺序存储一组值
我认为这是你正在寻找的东西。对于$key1
的每个值,它将$key2
的排序值存储在数组中并打印出来
use strict;
use warnings 'all';
my %hash = (
name1 => {
a => { line => 4, page => 112 },
b => { line => 6, page => 134 },
c => { line => 1, page => 112 },
},
name2 => {
a => { line => 43, page => 112 },
b => { line => 12, page => 134 },
c => { line => 55, page => 112 },
},
);
for my $key1 ( sort keys %hash ) {
my $h2 = $hash{$key1};
my @key2 = sort { $h2->{$a}{line} <=> $h2->{$b}{line} } keys %$h2;
print "$key1: @key2\n";
}
name1: c a b
name2: b a c