Hi

I am new to perl programming and i have one query and a problem in perl hashing.

I have two hashes containing

Hash 1 Hash 2
a=> 1 1 => c1
b=> 2 2 => c2
c=> 1 3 => c3
d=> 1
e=> 2
f => 3

I want to retrive the Keys of Hash1 from the keys of Hash 2.The Keys of hash matches the values of Hash1. How can i do this.

Hi,

Since you know hash 2 keys relate with hash 1 values, you can just say, print hash 1 key, when hash 1 value equals hash 2 key. Bingo!!! You are done.
Like so:

use warnings;
use strict;

my %hash1 = (
    a => 1,
    b => 2,
    c => 1,
    d => 1,
    e => 2,
    f => 3,
);

my %hash2 = (
    1 => 'c1',
    2 => 'c2',
    3 => 'c3',
);

for my $val_needed ( sort { $a cmp $b } keys %hash1 ) {
    for ( sort { $a <=> $b } keys %hash2 ) {
        print $val_needed, $/ if $hash1{$val_needed} == $_;
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.