0

我想对以下哈希进行排序。parentXX 应该使用 __displayorder 的值进行排序,parent 的 Xtopic 和 topic 的 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,
          }
      }
  }
}
4

2 回答 2

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];
于 2013-09-11T13:37:07.070 回答
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;
于 2013-09-11T15:40:20.957 回答