如何在Perl中按二级哈希值排序?

时间:2009-09-30 02:33:51

标签: perl hash sorting numbers ordinal

my $hash_ref = {
    one   => { val => 1, name => 'one'  },
    three => { val => 3, name => 'three'},
    two   => { val => 2, name => 'two'  },
};

我想对$hash_ref进行排序,以便foreach通过

命令它们
$hash_ref->{$key}->{'val'}

one
two
three

有什么建议吗?

3 个答案:

答案 0 :(得分:8)

@sorted_list是对已排序哈希元素的引用数组:

 @sorted_list = sort { $a->{'val'} <=> $b->{'val'} } values %{$unsorted_hash_ref};

您可以像这样使用它:

#!/usr/bin/perl

my $hash_ref = {
    one   => { val => 1, name => 'one' },
    three => { val => 3, name => 'three' },
    two   => { val => 2, name => 'two' },
};

foreach $elem ( sort { $a->{'val'} <=> $b->{'val'} } values %{$hash_ref} ) {
    print "$elem->{'val'} : $elem->{'name'}\n";
}

输出:

1 : one
2 : two
3 : three

答案 1 :(得分:0)

哈希表没有任何特定的顺序。但是,您可以对数组中的键进行排序,并使用它来遍历哈希:

my $hash_ref = {
    one => { val => 1, name => 'one'},
    three => { val => 3, name => 'three'},
    two => { val => 2, name => 'two'},
};

use strict;
use warnings;
use Lingua::EN::Words2Nums;

foreach my $key (sort { words2nums($a) <=> words2nums($b) } keys %$hash_ref)
{
    # do something with $hash_ref->{$key}
    print "processing key $key.\n";
}

您可以将任何您喜欢的内容定义为排序方法;有关详细信息,请参阅perldoc -f sort。从序数字文本到算术值的转换是用Lingua::EN::Words2Nums完成的(它也是基数)。

答案 2 :(得分:0)

#!/usr/bin/perl


my $hash_ref = (
                one   => {val => 1,  name => "one"},
                three => {val => 3,  name => "three"},
                two   => {val => 2,  name => 'two'},
               );

foreach $elem( sort {$$hash_ref{$a}{val} <=> $$hash_ref{$b}{val}} keys %$hash_ref){
    my $value = $hash_ref->{$elem}{val};
    my $name = $hash_ref->{$elem}{name};
    print "$name -> $value\n";
}

OutPut:
one -> 1
two -> 2
three -> 3