【问题标题】:Print multidimensional array in Perl, with keys在 Perl 中打印多维数组,带键
【发布时间】:2016-12-24 08:46:06
【问题描述】:

我在 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 引用。

【问题讨论】:

  • 第1000行是哪一个?
  • $foo_bar 是 hashref,而不是 arrayref
  • 这是一个好问题.. 脚本中没有 1000 行。 417行是:foreach my $fb(@$foo_bar){
  • 啊,我没有看到 417。这可能是因为你有一个打开的文件句柄。如果是这样,请不要使用全局文件句柄 (INFILE)。请改用词法文件句柄 ($fh)。
  • 不需要 $foo_bar->{"foo"} //= []; 行。 Perl 在需要时(有时在不需要时)自动激活结构。

标签: arrays perl multidimensional-array hash


【解决方案1】:

您需要将$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"
    ]
}

【讨论】:

  • @robertwojnar 请注意,这将以任意顺序获取密钥;如果您先要 foo,然后是 bar,您需要明确地这样做:foreach my $key ( 'foo', 'bar' ) 或将所需的顺序保留在单独的数组中
  • 我认为 ysth 的意思是如果您需要它们以 特定的 顺序。
猜你喜欢
  • 2016-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多