Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash merge/concatenation

this is a dump of my hashes: %hash1

$VAR1 = {
    abc => {
        123 => [
          'xx',
          'yy',
          'zy'
        ],
        456 => [
          'ab',
          'cd',
          'ef'
        ]
    }
};

and the second one: %hash2

$VAR2 = { 
    def => {
        659 => [
            'wx',
            'yg',
            'kl'
        ],
        456 => [
            'as',
            'sd',
            'df'
        ]
    },
    abc => {
        987 => [
            'lk',
            'dm',
            'sd'
        ]
    }
};

Now I want to merge these two hashes in a new hash, but if a key is duplicated (here 'abc'), the values should be appended, not replaced, so the keys should remain unique, and all the values should be retained as well. How can this be done in Perl? The output should be as follows:

$VAR1 = {
    def => {
        659 => [
            'wx',
            'yg',
            'kl'
        ],
        456 => [
            'as',
            'sd',
            'df'
        ]
    },
    abc => {
        987 => [
            'lk',
            'dm',
            'sd'
        ],
        123 => [
            'xx',
            'yy',
            'zy'
        ],
        456 => [
            'ab',
            'cd',
            'ef'
        ]
    }
 };
like image 860
Mahfuzur Rahman Pallab Avatar asked Sep 24 '12 14:09

Mahfuzur Rahman Pallab


1 Answers

Use the CPAN modules Hash::Merge or Hash::Merge::Simple. The first is highly configurable and the second is very simple to use.

like image 115
PSIAlt Avatar answered Oct 29 '22 18:10

PSIAlt