0

I have recursively put together an array of hashes for perl, which looks something like this :

[
    {
        'Default' => {
            'Elect' => { 'P' => 1 }
        }
    },
    {
        'Default' => {
            'Elect' => { 'A' => 1 }
        }
    },
    {
        'Default' => {
            'Elect' => { 'M' => 1 }
        }
    },
    {
        'Default' => {
            'Elect' => { 'I' => 1 }
        }
    },
    {
        'Default' => {
            'Picker' => { 'L' => 1 }
        }
    },
]

My aim is to make this more condensed and look like a single hash, as compared to array of hashes. Is there anyway in which i can make this array of hashes look like a hash:

{
    'Default' =>{
        'Elect' =>{
            'P' => 1,
            'A' => 1,
            'M' => 1,
            'I' => 1,
        },
        'Picker' => {
            'L' => 1
        }
    }
}
1
  • 3
    Where are you getting the array of hashes from in the first place? We could certainly show you how to modify your array as you requested, but it might be better to build the proper data structure right from the beginning, if possible. Commented Mar 13, 2014 at 16:50

1 Answer 1

2

Well, here is a simple recursive procedure to merge two hash references:

sub merge {
    my ($xs, $ys) = @_;
    while (my ($k, $v) = each %$ys) {
        if ('HASH' eq ref $v) {
            merge($xs->{$k} //= {}, $v);
        }
        else {
            $xs->{$k} = $v;
        }
    }
}

Then:

my $data = ...; # your input data structure
my $acc = {};
merge($acc, $_) for @$data;

which produces the result you desire in $acc.

There is also the Hash::Merge module, with that:

use Hash::Merge 'merge';
my $acc = {};
$acc = merge $acc, $_ for @$data;
Sign up to request clarification or add additional context in comments.

3 Comments

You are almost right. the problem is that $xs gets re initialised everytime . So if you rather pass $_[0] instead of $xs it works perfect. Thanks
@user2583714 I tested my code. It works just fine, because both inputs are references. Giving them names like $xs and $ys does not prevent correct functionality in this case, and makes the code much more comfortable to read.
Maybe i was doing something wrong . Working perfect for me , my way . Thanks a lot anyways

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.