Reputation: 459
I want to create a hash which contains key's values which are common in two hashes. In the below code, "test1" is available in two hashes values. Hence get the key value of both hashes, store it in array and create a new hash
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
}
}
}
}
}
Upvotes: 0
Views: 696
Reputation: 35198
First a note. To create an array as a value of a hash, you can use an anonymous array ref instead of creating a temporary array variable to later to take a references of:
$hash{key} = [ 'an', 'anonymous', 'array', 'ref' ];
Second, to find values that match between two arrays, check out: How do I compute the difference of two arrays? How do I compute the intersection of two arrays?
I'm afraid that your overall goal is a little unclear. If it's just to find element values that match between the two hashes, then all you need is a %seen style hash:
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";
Outputs:
test1 test2 test4 test6 test7 test9
Upvotes: 3