Search code examples
arraysperlmergeuniquehashref

Merge Perl Hashrefs and unique


I havve got two perl hashes with the following contenct:

First:

$VAR1 = {
      'name1' => [
                   'adam',
                   'bob'
                 ],
      'name2' => [
                  'Miller',
                  'Schumacher'
                ]
    };

Second:

$VAR1 = {
      'name1' => [
                   'tina',
                   'jason',
                   'jeff'
                 ],
      'name2' => [
                  'Miller',
                  'Schumacher',
                  'Schmidt'
                ]
    };

How can I merge them both to get the following structure and to get unique items in name2 ?

$VAR1 = {
      'name1' => [
                   'tina',
                   'jason',
                   'jeff',
                   'adam',
                   'bob',
                 ],
      'name2' => [
                  'Miller',
                  'Schumacher',
                  'Schmidt'
                ]
    };

Solution

  • You'll have to loop over name1, name2 keys and filter duplicates out of $VAR2->{$k} and $VAR1->{$k} arrays,

    use strict;
    use warnings;
    
    my $VAR1 = {
          'name1' => [ 'adam', 'bob' ],
          'name2' => [ 'Miller', 'Schumacher' ]
    };
    my $VAR2 = {
          'name1' => [ 'tina', 'jason', 'jeff' ],
          'name2' => [ 'Miller', 'Schumacher', 'Schmidt' ]
    };
    
    my %result;
    for my $k (keys %$VAR1) {
      my %seen;
      $result{$k} = [
        grep { !$seen{$_}++ } @{ $VAR2->{$k} }, @{ $VAR1->{$k} }
      ];
    }
    
    use Data::Dumper;
    print Dumper \%result;
    

    output

    $VAR1 = {
          'name2' => [
                       'Miller',
                       'Schumacher',
                       'Schmidt'
                     ],
          'name1' => [
                       'tina',
                       'jason',
                       'jeff',
                       'adam',
                       'bob'
                     ]
        };