I have a need of inserting an array of arrays into an array.And this whole array is a value for a key in a hash.i meant hash should look like this:

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

where one is the key here and remaining part if the value of for that key in the hash. observe that the array of arrays [3,4] and [5,6] is the third element in the actual array. the first two elements are 1 and 2.

I have written a small program for doing the same.

#!/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);

But this prints as below:

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

I can see that the array of arrays is not inserted into the array. could anybody help me with this?

有帮助吗?

解决方案 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);

Output:

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

Updated:

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

其他提示

First, a note: Only pass scalars to Dumper. If you want to dump an array or hash, pass a reference.

Then there's the question of what you expect. You say you expect

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

But I think you really expect

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

Both errors have the same cause.

[ ... ]

means

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

so

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

is assigning a single element to @a (a reference to an anonymous array) an a single element to @b (a reference to a different anonymous array).

You actually want

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

So from

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

you get

{
  "one" => [
    1,
    2,
    [
      3,
      4
    ],
    [
      5,
      6
    ]
  ]
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top