【问题标题】:How do I sort hash of hashes by value using perl?如何使用 perl 按值对哈希值进行排序?
【发布时间】:2011-06-08 00:03:24
【问题描述】:

我有这个代码

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 对其进行排序。

【问题讨论】:

  • 如果你的哈希键是数字的,hashrefs 数组是否更适合保存数据? (可能不是,但值得考虑)
  • 随机观察:应避免使用$a$b,因为它们与现有的全局变量冲突。

标签: perl sorting hash


【解决方案1】:
#!/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} );
}

【讨论】:

    【解决方案2】:
    print "$_->{Make} $_->{Color}" for  
       sort {
          $b->{Make} cmp $a->{Make}
           } values %hash;
    

    【讨论】:

      【解决方案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";
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-29
        • 2010-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-10
        • 2011-02-02
        • 1970-01-01
        相关资源
        最近更新 更多