如何使用Perl按值排序哈希的哈希?

4

我有这段代码

use strict;
use warnings;

my %hash;
$hash{'1'}= {'Make' => 'Toyota','Color' => 'Red',};
$hash{'2'}= {'Make' => 'Ford','Color' => 'Blue',};
$hash{'3'}= {'Make' => 'Honda','Color' => 'Yellow',};

foreach my $key (keys %hash){       
  my $a = $hash{$key}{'Make'};   
  my $b = $hash{$key}{'Color'};   
  print "$a $b\n";
}

需要按制造商对其进行排序。

丰田红色 本田黄色 福特蓝色


5
如果你的哈希键是数字,那么一个哈希引用数组可能更适合保存数据(这不一定是最好的选择,但值得考虑)。 - plusplus
5
随机观察:应避免使用“$a”和“$b”,因为它们与现有的全局变量冲突。 - darch
3个回答

11
#!/usr/bin/perl

use strict;
use warnings;

my %hash = (
    1 => { Make => 'Toyota', Color => 'Red', },
    2 => { Make => 'Ford',   Color => 'Blue', },
    3 => { Make => 'Honda',  Color => 'Yellow', },
);

# if you still need the keys...
foreach my $key (    #
    sort { $hash{$a}->{Make} cmp $hash{$b}->{Make} }    #
    keys %hash
    )
{
    my $value = $hash{$key};
    printf( "%s %s\n", $value->{Make}, $value->{Color} );
}

# if you don't...
foreach my $value (                                     #
    sort { $a->{Make} cmp $b->{Make} }                  #
    values %hash
    )
{
    printf( "%s %s\n", $value->{Make}, $value->{Color} );
}

4
print "$_->{Make} $_->{Color}" for  
   sort {
      $b->{Make} cmp $a->{Make}
       } values %hash;

3

plusplus是对的...数组哈希引用可能更好地选择数据结构。它还更具可扩展性;使用push添加更多汽车:

my @cars = (
             { make => 'Toyota', Color => 'Red'    },
             { make => 'Ford'  , Color => 'Blue'   },
             { make => 'Honda' , Color => 'Yellow' },
           );

foreach my $car ( sort { $a->{make} cmp $b->{make} } @cars ) {

    foreach my $attribute ( keys %{ $car } ) {

        print $attribute, ' : ', $car->{$attribute}, "\n";
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接