perl散列哈希 - 用于eacy键组内键和各自的值

时间:2016-03-22 20:24:12

标签: perl

我有一个从json检索到的散列哈希值,我试图压缩散列值,分组和打印值。也就是说,对于每个key1组,所有键和相应的值。尽管使用下面的代码在perl中实现这一点,但是,它打印单个值,每个ID和名称,但不是分组值。你能帮我解决一下如何分组和打印键和值。

数据:

VAR1= {
        'ID1' => {'Name1' => {'Address1' => {'Mod1' => ['pol1']}},
                  Name2' => {'Address1' => {'Mod2' => ['pol2']}}},
        'ID2' => {'Name3' => {'Address3' => {'Mod3' => ['pol3']}}},
        'ID3' => {'Name4' => {'Address4' => {'Mod4' => ['pol1, pol2, pol3']}}}
}

预期产出:

ID1 => [Name1,Address1,mod1(pol1), Name2,Address1,mod2(pol2)],
ID2 => [Name3,Address3,mod3(pol3)],
ID3 => [Name4,Address4,mod4(pol1,pol2,pol3)]

代码1:

for my $id (@id_list) {
     foreach my $item (sort (slurp(\%{$new{$id}}))) {
     my $data = join(',', @$item);
     print "data..  $data\n";
     push(@results,$data);
  } 
}

print map {"$_"}  @results;

代码2:

foreach my $id (sort keys %new){
   foreach my $name (keys %{$new{$id} }) {
      foreach my $address (keys %{$new{$id}{$name}}) {
         foreach my $mod (keys %{$new{$id}{$name}{$address}) {
            foreach my $value (@{$new{$id}{$name}{$address}{$mod}}) {
               my $sp = ":";
               my $reasons = join(',',$id,$name,$address,$mod,$value.$sp);
               push (@rea, $reasons);
            }
         }
      }
   }
}

1 个答案:

答案 0 :(得分:1)

使用这样的嵌套结构,您需要系统地进行,例如在“ Code2 ”中。

use warnings;
use strict;
use feature qw(say);

my %id_list = ( 
    ID1 => { 
        Name1 => {'Address1' => {'Mod1' => ['pol1']}}, 
        Name2 => {'Address1' => {'Mod2' => ['pol2']}}
    },  
    ID2 => { 'Name3' => {'Address3' => {'Mod3' => ['pol3']}} },
    ID3 => { 'Name4' => {'Address4' => {'Mod4' => ['pol1, pol2, pol3']}} }
);

my (%flattened, @ar, $modvals);
foreach my $id (sort keys %id_list){
    foreach my $name (keys %{$id_list{$id} }) {
        foreach my $address (keys %{$id_list{$id}{$name}}) {
            foreach my $mod (keys %{$id_list{$id}{$name}{$address}}) {
                $modvals = "$mod(" . 
                    join(',', @{$id_list{$id}{$name}{$address}{$mod}})
                    . ')';
                $modvals =~ s/,$//; # strip the last comma
                push @ar, $name, $address, $modvals;
            }   
        }   
    }
    $flattened{$id} = [ @ar ];
    @ar = ();
}

say "$_ => @{$h{$_}}" for sort keys %flattened;

输出

ID1 => Name1 Address1 Mod1(pol1) Name2 Address1 Mod2(pol2)
ID2 => Name3 Address3 Mod3(pol3)
ID3 => Name4 Address4 Mod4(pol1, pol2, pol3)

这会将mod3的字符串生成为(pol1, ...) - 如输入中所示,作为字符串。如果在输入中将pol列为pol,则id之间的空格将在输出中消失。

生成具有Event个键的哈希和具有相应条目的数组引用。