简体   繁体   English

合并包含公用键和值的散列,perl

[英]Merging hashes containing common keys and values, perl

For example, we have two hashes. 例如,我们有两个哈希。 We don't know their size, but we know that they have common data 我们不知道它们的大小,但是我们知道它们具有共同的数据

%h1 = (
    k1 => (a => "a1",
           b => "b1"),
    k2 => (a => "a2",
           b => "b2")
    k3 => (a => "a3",
           b => "b3"),
    k4 => (a => "a4",
           b => "b4")
);
%h2 = (
    k2 => (c => "c2",
           b => "b2"),
    k3 => (c => "c3",
           b => "b3")
    k4 => (c => "c4",
           b => "b")
)

How to merge them to get something like this? 如何合并它们以获得类似的东西? Note, that exact keys are unknown, but has common keys-values. 请注意,确切的键是未知的,但是具有通用的键值。

%h3 = (
        k1 => (a => "a1",
               b => "b1",
               c => "0"),
        k2 => (a => "a2",
               b => "b2",
               c => "c2"),
        k3 => (a => "a3",
               b => "b3",
               c => "c3"),
        k4 => (a => "a4",
               b => "b4",
               c => "c4")
    )

You can try something like this: 您可以尝试如下操作:

use strict;
use warnings;
use Data::Dumper;
$Data::Dumper::Terse = 1;

my %h1 = (
    k1 => {a => "a1",
           b => "b1"},
    k2 => {a => "a2",
           b => "b2"},
    k3 => {a => "a3",
           b => "b3"},
    k4 => {a => "a4",
           b => "b4"}
);
my %h2 = (
    k2 => {c => "c2",
           b => "b2"},
    k3 => {c => "c3",
           b => "b3"},
    k4 => {c => "c4",
           b => "b"}
);

my $h3 = merge( \%h1, \%h2 );
print Dumper( $h3 );

sub merge {
    my ( $h1, $h2 ) = @_;

    my @keys = keys %{ {map {$_ => 1} keys %$h1, keys %$h2} };
    my @sub_keys = keys %{ {map {$_ => 1} map { keys %{ $_ } } values %$h1, values %$h2} };

    my %h;
    for my $k1 (@keys) {
        for my $k2 (@sub_keys) {
            $h{$k1}{$k2} = $h1->{$k1}{$k2} // $h2->{$k1}{$k2} // "0";
        }
    }
    return \%h;
}

Output : 输出

{      
  'k1' => {
            'b' => 'b1',
            'c' => '0',
            'a' => 'a1'
          },
  'k2' => {
            'a' => 'a2',
            'b' => 'b2',
            'c' => 'c2'
          },
  'k3' => {
            'c' => 'c3',
            'b' => 'b3',
            'a' => 'a3'
          },
  'k4' => {
            'a' => 'a4',
            'c' => 'c4',
            'b' => 'b4'
          }
}

Try this 尝试这个

my %h3;
for my $k1 (keys %h1)
{

     $h3{$k1} = ($h2{$k1})?\(%{$h1{$k1}},%{$h2{$k1}}):\%{$h1{$k1}};
     delete $h2{$k1};   
}

for my $k2 (keys %h2)
{
    $h3{$k2} = \%{$h2{$k2}};
}

print Dumper \%h3;

Note: %h2 keys are deleted. 注意: %h2键被删除。 If you want %h2 value, please make a copy before looping 如果您需要%h2值,请在循环之前进行复制

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM