Search code examples
arraysperlhashperl-data-structureshash-of-hashes

Perl: inserting array of arrays in into a array which is a value for a key


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?


Solution

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