根据最终哈希值

时间:2017-03-09 06:45:02

标签: perl sorting hash

我有一个嵌套哈希如下

$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排列为cabname2应该包含b,{{ 1}},a

我知道哈希总是给出随机对,但有没有办法对值进行系统排列以获得排序键?

2 个答案:

答案 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