2 sorting perl hash numbers ordinal
my $hash_ref = {
one => { val => 1, name => 'one' },
three => { val => 3, name => 'three'},
two => { val => 2, name => 'two' },
};
Run Code Online (Sandbox Code Playgroud)
我想排序$hash_ref一个foreach将它们命令
$hash_ref->{$key}->{'val'}
one
two
three
Run Code Online (Sandbox Code Playgroud)
有什么建议?
@sorted_list 是对已排序的哈希元素的引用数组:
@sorted_list = sort { $a->{'val'} <=> $b->{'val'} } values %{$unsorted_hash_ref};
Run Code Online (Sandbox Code Playgroud)
您可以像这样使用它:
#!/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";
}
Run Code Online (Sandbox Code Playgroud)
输出:
1 : one
2 : two
3 : three
Run Code Online (Sandbox Code Playgroud)