Perl 如何将2个哈希拆分为3个哈希?
在以下情况下,如何将包含一些常用键的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
%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开始)
或者使用perl5.20+
和哈希切片
my %o_hash_1 = %i_hash_1{ grep !exists $i_hash_2{$_}, keys %i_hash_1};
或
或者使用List::Util
中的pairmap
(从v1.29开始)
或者使用perl5.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};