【问题标题】:Perl: inserting array of arrays in into a array which is a value for a keyPerl:将数组数组插入到作为键值的数组中
【发布时间】:2013-06-02 00:37:34
【问题描述】:

我需要将一个数组插入到一个数组中。整个数组是哈希中键的值。我的意思是哈希应该如下所示:

"one"
[
  [
    1,
    2,
  [
    [
      3,
      4
    ],
    [
      5,
      6
    ]
  ]
]
]

其中一个是这里的键,其余部分是散列中该键的值。 观察数组 [3,4] 和 [5,6] 的数组是实际数组中的第三个元素。前两个元素是 1 和 2。

我写了一个小程序来做同样的事情。

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
$Data::Dumper::Terse = 1;
$Data::Dumper::Indent = 1;
$Data::Dumper::Useqq = 1;
$Data::Dumper::Deparse = 1;

my %hsh;
my @a=[1,2];
my @b=[[3,4],[5,6]];
$hsh{"one"}=\@a;
push @{$hsh{"one"}},@b;
print Dumper(%hsh);

但打印如下:

"one"
[
  [
    1,
    2
  ],   #here is where i see the problem.
  [
    [
      3,
      4
    ],
    [
      5,
      6
    ]
  ]
]

我可以看到数组的数组没有插入到数组中。 有人可以帮我解决这个问题吗?

【问题讨论】:

  • [...] 创建一个数组引用,而不是一个数组。所以@a=[1,2] 创建了一个包含一个元素的数组。这可能是您问题的根源,但我不确定:您预期的数据结构的意图令人困惑。 @a=(1,2) 将创建一个包含两个元素的数组。你确定不要%hsh = ( one => [1, 2, [ 3, 4 ], [5, 6]] )

标签: arrays perl hash perl-data-structures hash-of-hashes


【解决方案1】:

首先,请注意:仅将标量传递给Dumper。如果要转储数组或哈希,请传递引用。

然后是您期望的问题。你说你期待

[ [ 1, 2, [ [ 3, 4 ], [5, 6] ] ] ]

但我想你真的很期待

[ 1, 2, [ [ 3, 4 ], [5, 6] ] ]

这两个错误的原因相同。

[ ... ]

意思

do { my @anon = ( ... ); \@anon }

所以

my @a=[1,2];
my @b=[[3,4],[5,6]];

将单个元素分配给@a(对匿名数组的引用),将单个元素分配给@b(对不同匿名数组的引用)。

你真的想要

my @a=(1,2);
my @b=([3,4],[5,6]);

所以从

my %hsh;
$hsh{"one"}=\@a;
push @{$hsh{"one"}},@b;
print(Dumper(\%hsh));

你得到

{
  "one" => [
    1,
    2,
    [
      3,
      4
    ],
    [
      5,
      6
    ]
  ]
}

【讨论】:

    【解决方案2】:
    use strict;
    use warnings;
    use Data::Dumper;
    $Data::Dumper::Terse = 1;
    $Data::Dumper::Indent = 1;
    $Data::Dumper::Useqq = 1;
    $Data::Dumper::Deparse = 1;
    
    my %hsh;
    my @a=(1,2); # this should be list not array ref
    my @b=([3,4],[5,6]); # this should be list conatining array ref
    push (@a, \@b); #pushing ref of @b
    push (@{$hsh{'one'}}, \@a); #pushing ref of @a
    
    print Dumper(%hsh);
    

    输出:

    "one"
    [
      [
        1,
        2,
        [
          [
            3,
            4
          ],
          [
            5,
            6
          ]
        ]
      ]
    ]
    

    更新:

    my %hsh;
    my @a=( 1,2 );
    my @b=( [3,4],[5,6] );
    push (@a, @b); # removed ref of @b
    push (@{$hsh{'one'}}, @a); #removed ref of @a
    
    print Dumper(\%hsh);
    
    Output:
    {
      "one" => [
        1,
        2,
        [
          3,
          4
        ],
        [
          5,
          6
        ]
      ]
    }
    

    【讨论】:

    • 就是这样。谢谢尼基尔
    • 你确定是这样吗?你似乎有一个额外的数组。看我的回答。
    猜你喜欢
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多