-4

我有一组对哈希的引用:

@array=($ref1,$ref2,$ref3);

每个 ref 指向具有相同键但不同值的散列。我必须根据 KEY 的值(散列中的键之一)对散列进行排序。稍后我必须打印出所有散列的所有键的值,但已排序。

例子:

%h1=(KEY=>1,name=>John,sport=>football);
%h2=(KEY=>52,name=>Kate,sport=>football);
%h3=(KEY=>7,name=>April,sport=>basketball);

结果我想按顺序得到它:

%h1,%h3,%h2

4

1 回答 1

0

例子:

use strict;
use warnings; 

my %h1=(KEY=>1,name=>'John',sport=>'football');
my %h2=(KEY=>52,name=>'Kate',sport=>'football');
my %h3=(KEY=>7,name=>'April',sport=>'basketball');
my @array=(\%h1,\%h2,\%h3);

for my $h (sort {$a->{KEY} <=> $b->{KEY} } @array) {
    print join(",", map { "$_, $h->{$_}"} keys %$h ), "\n";
}

输出

KEY, 1,name, John,sport, football
KEY, 7,name, April,sport, basketball
KEY, 52,name, Kate,sport, football
于 2013-05-29T22:06:21.083 回答