我想创建一个哈希,其中包含两个哈希中常见的键值。在下面的代码中,“test1”有两个哈希值。因此,获取两个哈希的键值,将其存储在数组中并创建一个新的哈希
use strict;
use warnings;
my @array1 = ( "test1", "test2", "test3" );
my @array2 = ( "test4", "test5", "test6" );
my @array3 = ( "test7", "test8", "test9" );
my %hashids = ( "1" => \@array1, "2" => \@array2, "3" => \@array3 );
my @targetarray1 = ( "test1", "test2", "test99" );
my @targetarray2 = ( "test4", "test6", "test100" );
my @targetarray3 = ( "test7", "test9", "test66" );
my %hashtarget_ids = ( "a" => \@targetarray1, "b" => \@targetarray2, "c" => \@targetarray3 );
my %finalhash;
my $i;
for my $itemarray ( values %hashids ) {
for my $arrayval (@$itemarray) {
for my $temp ( values %hashtarget_ids ) {
for my $temp_text (@$temp) {
if ( $arrayval eq $temp_text ) {
$i++;
my @final_array;
#print $hashtarget_ids[$$temp],"\n"; ##Print key value here as "a"
#print $hashids[$$temp],"\n"; ##Print key value here as "1"
#push @finalarray,$hashtarget_ids[$$temp]; ##Push key value to array
#push @finalarray,$hash_ids[$$temp]; ##Push key value to array
#%finalhash=("$i"=>\@final_array); ##Create hash
}
}
}
}
}
答案 0 :(得分:2)
首先说明一下。要将数组创建为散列值,可以使用匿名数组ref而不是创建临时数组变量,以便稍后引用:
$hash{key} = [ 'an', 'anonymous', 'array', 'ref' ];
其次,要查找两个数组之间匹配的值,请查看:How do I compute the difference of two arrays? How do I compute the intersection of two arrays?
我担心你的总体目标有点不清楚。如果只是为了找到两个哈希值之间匹配的元素值,那么您只需要看到%样式哈希:
use strict;
use warnings;
my %hashids = (
"1" => [ "test1", "test2", "test3" ],
"2" => [ "test4", "test5", "test6" ],
"3" => [ "test7", "test8", "test9" ]
);
my %hashtarget_ids = (
"a" => [ "test1", "test2", "test99" ],
"b" => [ "test4", "test6", "test100" ],
"c" => [ "test7", "test9", "test66" ]
);
my %seen;
$seen{$_}++ for map {@$_} values %hashids;
my @final_array = sort grep {$seen{$_}} map {@$_} values %hashtarget_ids;
print "@final_array\n";
输出:
test1 test2 test4 test6 test7 test9