in reply to Retrieving Key and Value Hashes

You want to print matching values and the first key? The shared/matching keys will be identical, so the key becomes ambiguous.. Try the following code. It uses anonymous hashes and a subroutine.

use strict; use warnings; use Data::Dumper; my $hash1 = {qw/ name1 ABCD name2 BCD name3 ASCDA name4 AAAAA /}; my $hash2 = {qw/ name1 0.2 name5 0.3 name4 0.0002 name7 0.222 /}; my $hash_result = sub{ my ($hash1,$hash2) = @_; foreach my $key (sort keys $hash1){ print "\'hash1 value: $hash1->{$key}\' AND \'hash2 value: $has +h2->{$key}\' AND shared key: \'$key\'\n" if(defined($hash2->{$key})); } }; $hash_result->($hash1, $hash2);

My output:
rsx491@temple:~/Perl/test$ perl hash_compare.pl 'hash1 value: ABCD' AND 'hash2 value: 0.2' AND shared key: 'name1' 'hash1 value: AAAAA' AND 'hash2 value: 0.0002' AND shared key: 'name4'

Replies are listed 'Best First'.
Re^2: Retrieving Key and Value Hashes
by rsx491 (Novice) on Jul 05, 2015 at 11:40 UTC

    Or just return a nested 3rd hash with the matching key/values.

    use strict; use warnings; use Data::Dumper; my $hash1 = {qw/ name1 ABCD name2 BCD name3 ASCDA name4 AAAAA /}; my $hash2 = {qw/ name1 0.2 name5 0.3 name4 0.0002 name7 0.222 /}; my %hash3 = &{sub{ my ($hash1,$hash2,) = @_; my %hash3; foreach my $key (sort keys $hash1){ if(defined($hash2->{$key})){ $hash3{'hash1_values'}{$key} = $hash1->{$key}; $hash3{'hash2_values'}{$key} = $hash2->{$key}; } } return %hash3; }}($hash1, $hash2); print Dumper(sort %hash3);

    My output:
    rsx491@temple:~/Perl/test$ perl hash_compare_return_hash.pl
    $VAR1 = { 'name1' => '0.2', 'name4' => '0.0002' };
    $VAR2 = { 'name1' => 'ABCD', 'name4' => 'AAAAA' };
    $VAR3 = 'hash1_values';
    $VAR4 = 'hash2_values';