如何使用perl按子键/值对散列哈希进行排序?

时间:2013-09-11 13:28:53

标签: perl sorting hash

我想要对以下哈希进行排序。 parentXX应该使用__displayorder的值进行排序,父对象的Xtopic和主题的Xprod应按字母顺序排序。

$VAR1 = {
   'views' => {
      'parent23' => {
          '__displayorder' => 2,
          'vtopic1' => {
              'gprod1.1' => undef,
              'aprod1.2' => undef,
          },
          'btopic2' => {
              'tprod2.1' => undef,
              'mprod2.2' => undef,
          },
      },
      'parent98' => {
          '__displayorder' => 1,
          'atopic1' => {
              'qprod1.1' => undef,
              'jprod1.2' => undef,
          },
          'xtopic2' => {
              'kprod2.1' => undef,
              'fprod2.2' => undef,
          }
      }
  }
}

2 个答案:

答案 0 :(得分:1)

您无法对哈希进行排序。您能否按照特定顺序处理视图名称?

my $views = $VAR1->{views};
my @sorted_view_keys = sort {
        $views->{$a}{__displayorder} cmp $views->{$b}{__displayorder}
    } keys(%$views);

或许您想要排序的视图?

my @sorted_views = map { $views->{$_} } @sorted_view_keys;
   -or-
my @sorted_views = @$views[@sorted_view_keys];

答案 1 :(得分:0)

如前所述,您无法对普通的Perl哈希进行排序。 Perl哈希是无序的。但您可以使用CPAN模块Tie::IxHash来获取有序哈希。下面的行将您的示例输出中的所有子哈希转换为Tie::IxHash哈希并进行一些排序(例如按字母顺序或按显示顺序):

 use Tie::IxHash;
 my $views = $VAR1->{views};
 while(my($view_key, $view) = each %$views) {
     while(my($topic, $prods) = each %$view) {
         next if $topic =~ m{^__};
         tie my %new_prods, 'Tie::IxHash', (map { ($_ => $prods->{$_}) } sort keys %$prods);
         $view->{$topic} = \%new_prods;
     }
     tie my %new_view, 'Tie::IxHash', (map { ($_ => $view->{$_}) } sort keys %$view);
     $views->{$view_key} = \%new_view;
 }
 tie my %new_views, 'Tie::IxHash', (map { ($_ => $views->{$_}) } sort { $views->{$a}->{__displayorder} <=> $views->{$b}->{__displayorder} } keys %$views);
 $VAR1->{views} = \%new_views;