compare multiple hashes for common keys merge valu

2019-06-04 22:34发布

I have a working bit of code here where I am comparing the keys of six hashes together to find the ones that are common amongst all of them. I then combine the values from each hash into one value in a new hash. What I would like to do is make this scaleable. I would like to be able to easily go from comparing 3 hashes to 100 without having to go back into my code and altering it. Any thoughts on how I would achieve this? The rest of the code already works well for different input amounts, but this is the one part that has me stuck.

my $comparison = List::Compare->new([keys %{$posHashes[0]}], [keys %{$posHashes[1]}], [keys %{$posHashes[2]}], [keys %{$posHashes[3]}], [keys %{$posHashes[4]}], [keys %{$posHashes[5]}]);
my %comboHash;
for ($comparison->get_intersection) {
$comboHash{$_} = ($posHashes[0]{$_} . $posHashes[1]{$_} . $posHashes[2]{$_} . $posHashes[3]{$_} . $posHashes[4]{$_} . $posHashes[5]{$_});
}

4条回答
戒情不戒烟
2楼-- · 2019-06-04 23:10

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)};
查看更多
劫难
3楼-- · 2019-06-04 23:12
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} });
}
查看更多
可以哭但决不认输i
4楼-- · 2019-06-04 23:22

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);
查看更多
何必那么认真
5楼-- · 2019-06-04 23:26

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;
}
查看更多
登录 后发表回答