复杂的阵列/哈希

时间:2013-05-16 01:04:49

标签: perl

我在下面的表格中输入了需要在表格中转换(参见$ output)下面给出的,我确实看了现有的Q& As但没有找到任何相关的内容,有人可以帮我解决一下出来了?

$input = { 
           a => b,
           c => d,
           e => { 
                  f => {
                         g => [
                                {
                                  ab => 1111,
                                  ef => 3333
                                  ....
                                  ....
                                 },
                                {
                                  fd => 2222,
                                  as => 5555
                                  ....
                                  ....
                                }
                                .
                                .
                                .
                               ] } } };

$output = { 
           a => b,
           c => d,
           e => { 
                  f => {
                         g => { 
                                 1111 => {
                                            ef => 3333 
                                            ....   
                                            ....
                                           }
                                 5555 => {   
                                            fd => 2222
                                            ....
                                            ....
                                         }
                              }}}};

1 个答案:

答案 0 :(得分:0)

首先,您在问题中包含了无关紧要的内容。

问题是关于从

转换var($input->{e}{f}{g})的值
[
   {
      ab => 1111,
      ef => 3333,
      ...
   },
   {
      fd => 2222,
      as => 5555,
      ...
   },
   ...
]

{ 
   1111 => {
      ef => 3333,
      ...
   },
   5555 => {
      fd => 2222,
      ...
   },
   ...
}

删除无关位后,问题变得非常简单。代码看起来像:

my %keyed_recs;
for my $rec (@{ $input->{e}{f}{g} }) {
   my $key_field = ...;   # 'ab' or 'as'
   my $key = delete($rec->{$key_field});
   $keyed_recs{$key} = $rec;
}

$input->{e}{f}{g} = \%keyed_recs;

特别是如果关键字段的名称是常量,map可用于简洁。

$input->{e}{f}{g} = {
   map { delete($_->{id}) => $_ }
      @{ $input->{e}{f}{g} }
};
相关问题