rob*_*nar 1 arrays perl hash multidimensional-array
我在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";
Run Code Online (Sandbox Code Playgroud)
我想要的结果是:
我不知道..我正在尝试这个:
foreach my $fb(@$foo_bar){
}
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
不是./test.pl第417行1000行的ARRAY参考.
您需要迭代$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} } );
}
Run Code Online (Sandbox Code Playgroud)
它有助于使用Data :: Dumper或Data :: 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"
]
}
Run Code Online (Sandbox Code Playgroud)