使用键在Perl中打印多维数组

时间:2016-08-17 15:39:30

标签: arrays perl multidimensional-array hash

我在Perl中有这种数组:

my $foo_bar;

$foo_bar->{"foo"} //= [];
push @{$foo_bar->{"foo"}}, "foo1";
push @{$foo_bar->{"foo"}}, "foo2";
push @{$foo_bar->{"foo"}}, "foo3";

$foo_bar->{"bar"} //= [];
push @{$foo_bar->{"bar"}}, "bar1";
push @{$foo_bar->{"bar"}}, "bar2";
push @{$foo_bar->{"bar"}}, "bar3";

我想要的结果是:

  • foo:foo1,foo2,foo3
  • bar:bar1,bar2,bar3

我不知道......我正在尝试这个:

  foreach my $fb(@$foo_bar){

  }

我收到了一个错误:

  

不是./test.pl第417行第1000行的ARRAY参考。

1 个答案:

答案 0 :(得分:6)

您需要将$foo_bar迭代为散列引用,而不是作为数组引用。而且因为它是一个哈希,你需要先获取密钥然后再使用它们。

use feature 'say';

#                 | you only iterate the keys ...
#                 |    | this percent is for hash  
#                 V    V     
foreach my $key ( keys %{ $foo_bar } ) {

    #    | ... and use the key here 
    #    |                   | this one is an array ref
    #    |                   |  | ... and the value here
    #    |                   |  |
    #    V                   V  VVVVVVVVVVVVVVVV
    say "$key ", join( ', ', @{ $foo_bar->{$key} } );
}

使用Data::DumperData::Printer查看您的数据结构会很有帮助。这个是Data :: Printer,适合人类消费。

 \ {                  # curly braces are hash refs
    bar   [           # square braces are array refs   
        [0] "bar1",
        [1] "bar2",
        [2] "bar3"
    ],
    foo   [
        [0] "foo1",
        [1] "foo2",
        [2] "foo3"
    ]
}
相关问题