compare multiple hashes for common keys merge values

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-08 13:04:29
my %all;
for my $posHash (@posHashes) {
   for my $key (keys(%$posHash)) {
      push @{ $all{$key} }, $posHash->{$key};
   }
}

my %comboHash;
for my $key (keys(%all)) {
   next if @{ $all{$key} } != @posHashes;
   $comboHash{$key} = join('', @{ $all{$key} });
}

Just make a subroutine and pass it hash references

my $combination = combine(@posHashes);

sub combine {
    my @hashes = @_;
    my @keys;
    for my $href (@hashes) {
        push @keys, keys %$href;
    }
    # Insert intersection code here..
    # .....
    my %combo;
    for my $href (@hashes) {
        for my $key (@intersection) {
            $combo{$key} .= $href->{$key};
        }
    }
    return \%combo;
}

Create a subroutine:

sub combine_hashes {
  my %result = ();
  my @hashes = @_;
  my $first = shift @hashes;
  for my $element (keys %$first) {
    my $count = 0;
    for my $href (@hashes) {
      $count += (grep {$_ eq $element} (keys %$href));
    }
    if ($count > $#hashes) {
      $result{$element} = $first->{$element};
      $result{$element} .= $_->{$element} for @hashes;
    }
  }
  \%result;
}

and call it by:

my %h = %{combine_hashes(\%h1, \%h2, \%h3)};

...or as:

my %h = %{combine_hashes(@posHashes)};

There is pretty straightforward solution:

sub merge {
    my $first = shift;
    my @hashes = @_;
    my %result;
    KEY:
    for my $key (keys %$first) {
        my $accu = $first->{$key};
        for my $hash (@hashes) {
            next KEY unless exists $hash->{$key};
            $accu .= $hash->{$key};
        }
        $result{$key} = $accu;
    }
    return \%result;
}

You have to call it with references to hashes and it will return also hash reference e.g.:

my $comboHashRef = merge(@posHashes);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!