2
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

有什么建议么?

4

4 回答 4

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
于 2009-09-30T02:40:12.723 回答
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
于 2013-08-07T21:11:30.160 回答
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完成从序数数字文本到算术值的转换(它也处理基数)。

于 2009-09-30T02:52:46.303 回答
0
use strict;
use warnings;

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

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

output:
one -> 1
two -> 2
three -> 3
于 2013-01-07T07:30:01.607 回答