如何将2个哈希分成3个哈希?

时间:2014-06-29 12:08:14

标签: perl hash

在以下情况下,如何将包含一些常用键的2个哈希值拆分为3个哈希值:

%input_hash_1 = ( key1 => 1, key2 => 2, key3 => 3, , key4 => 4 );
%input_hash_2 = ( key3 => 3, key4 => 4, key5 => 5, , key6 => 6 );

,所需的输出是:

%output_hash_1 = ( key1 => 1, key2 => 2 );  # keys in input_hash_1 && not in input_hash_2
%output_hash_2 = ( key3 => 3, key4 => 4 );  # keys in input_hash_1 &&     in input_hash_2
%output_hash_3 = ( key5 => 5, key6 => 6 );  # keys in input_hash_2 && not in input_hash_1

在Perl。

2 个答案:

答案 0 :(得分:3)

使用哈希值设置操作很容易。

#!/usr/bin/perl
use warnings;
use strict;

use Data::Dumper;

my %hash1 = ( key1 => 1, key2 => 2, key3 => 3, key4 => 4 );
my %hash2 = ( key3 => 3, key4 => 4, key5 => 5, key6 => 6 );

my %both = %hash1;
exists $hash2{$_} or delete $both{$_} for keys %hash1;
print Dumper \%both;

my %only1 = %hash1;
delete @only1{ keys %hash2 };
print Dumper \%only1;

my %only2 = %hash2;
delete @only2{ keys %hash1 };
print Dumper \%only2;

另见Set::Light

答案 1 :(得分:1)

my %o_hash_1 = map { !exists $i_hash_2{$_} ? ($_=>$i_hash_1{$_}) : () } keys %i_hash_1;
my %o_hash_2 = map {  exists $i_hash_2{$_} ? ($_=>$i_hash_1{$_}) : () } keys %i_hash_1;
my %o_hash_3 = map { !exists $i_hash_1{$_} ? ($_=>$i_hash_2{$_}) : () } keys %i_hash_2;

my %o_hash_1 = map { $_=>$i_hash_1{$_} } grep !exists $i_hash_2{$_}, keys %i_hash_1;
my %o_hash_2 = map { $_=>$i_hash_1{$_} } grep  exists $i_hash_2{$_}, keys %i_hash_1;
my %o_hash_3 = map { $_=>$i_hash_2{$_} } grep !exists $i_hash_1{$_}, keys %i_hash_2;

或使用pairmap中的List::Util(自v1.29起)

use List::Util 'pairmap';
my %o_hash_1 = pairmap { !exists $i_hash_2{$a} ? ($a=>$b) : () } %i_hash_1;

或使用perl 5.20+key/value哈希切片

my %o_hash_1 = %i_hash_1{ grep !exists $i_hash_2{$_}, keys %i_hash_1};