如何使用perl按值对哈希值进行排序?

时间:2011-01-12 17:36:30

标签: perl sorting hash

我有这段代码

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";
}

这就出来了:

  

丰田红本田黄福特蓝

需要帮助按Make排序。

3 个答案:

答案 0 :(得分:10)

#!/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} );
}

答案 1 :(得分:4)

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

答案 2 :(得分:3)

plusplus是正确的......一个hashrefs数组可能是更好的数据结构选择。它也更具可扩展性;使用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";
    }
}