2014-06-29 56 views
1

如何我可以拆分2个散列,包含一些共同的密钥,为3个散列,当:如何将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

回答

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; 

,或者使用从pairmapList::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}; 
+0

哪一个更快? – user3787639

+0

@ user3787639首先应该更快,因为更少的操作。 –

+0

谢谢你的男人.. – user3787639

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见。