1

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

"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
    ]
  ]
]

我可以看到数组的数组没有插入到数组中。有人可以帮我吗?

4

2 回答 2

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
    ]
  ]
}
于 2013-06-06T06:26:02.400 回答
0
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
    ]
  ]
}
于 2013-06-06T06:21:14.967 回答