Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Perl 如何将2个哈希拆分为3个哈希?_Perl_Hash - Fatal编程技术网

Perl 如何将2个哈希拆分为3个哈希?

Perl 如何将2个哈希拆分为3个哈希?,perl,hash,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 ); # ke

在以下情况下,如何将包含一些常用键的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中。

使用哈希设置操作很容易

#!/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;

另请参见。

使用哈希设置操作很容易

#!/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;
另见

或者使用
List::Util
中的
pairmap
(从v1.29开始)

或者使用perl
5.20+
和哈希切片

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

或者使用
List::Util
中的
pairmap
(从v1.29开始)

或者使用perl
5.20+
和哈希切片

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

哪一个更快?@user3787639首先应该更快,因为操作更少。
delete${keys%i\u hash\u 2}for\my%o\u hash\u 1=%i\u hash\u 1(干诱惑)在5.20+中,可以使用kv哈希片而不是映射<代码>…=%i_hash_1{grep…}哪一个更快?@user3787639 first应该更快,因为操作更少。
删除\my%o_hash_1=%i_hash_1的@${keys%i_hash_2}(干诱惑)在5.20+中,可以使用kv哈希片而不是映射<代码>…=%i_hash_1{grep…}
my %o_hash_1 = %i_hash_1{ grep !exists $i_hash_2{$_}, keys %i_hash_1};