2011-01-12 88 views
4

我有這樣的代碼如何使用perl按值排序哈希散列?

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

而這一點放:

豐田紅本田黃色福特藍

需要幫助的出售信息吧。

+4

如果您的散列鍵是數字,那麼hashrefs數組是否更適合保存數據? (它可能不是,但值得考慮) – plusplus 2011-01-12 17:46:59

回答

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}); 
} 
4
print "$_->{Make} $_->{Color}" for 
    sort { 
     $b->{Make} cmp $a->{Make} 
     } values %hash; 
3

加加是正確的...... 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"; 
    } 
}