List keys that of same values from a Perl Hash

Suppose that we have a hash like this:

my %thehash = ( "abc" => {'a', 'office', '123'},
"cax" => {'s', 'domain', '254'},
"adm" => {'s', 'atwork', '254'},
"tec" => {'s', 'domain', '294'},
"ued" => {'s', 'domain', '254'}
);


How can we get a list of the keys that have same values from this hash?
To be specific, we need to get “cax”, “ued” in this example.

Here’s a good example that meets the needs:

1. #!/usr/bin/perl

2. my %hash = ( "abc" => {'a', 'office', '123'},
3.              "cax" => {'d', 'domain', '254'},
4.              "adm" => {'d', 'atwork', '254'},
5.              "tec" => {'d', 'domain', '294'},
6.              "ued" => {'d', 'domain', '254'},
7.            );
8.

9. my %key_set;
10. my $found;
11.

12. foreach my $key (keys %hash)
13. {
14.     $found = 0;
15.     foreach (keys %key_set) {
16.             if (is_hash_eq($hash{$_}, $hash{$key})) {
17.                     push @{$key_set{$_}}, $key;
18.                     $found = 1;
19.                     last;
20.             }
21.     }
22.
23.     if ($found == 0) {
24.             push @{$key_set{$key}}, $key;
25.     }
26.
27. }
28.
29. sub is_hash_eq {
30.         my ($h1, $h2) = @_;
31.         my $is_eq = 1;
32.
33.         foreach (keys %$h1) {
34.                  if (!exists ($$h2{$_}) || $$h1{$_} ne $$h2{$_}) {
35.                         $is_eq = 0;
36.                         last;
37.                 }
38.         }
39.
40.         return $is_eq;
41. }
42.
43. foreach (keys %key_set)
44. {
45.         print "@{$key_set{$_}}n" if(scalar(@{$key_set{$_}}) > 0);
46. }

Recommended documentation : Perl Hash Howto

Share Button

Leave a comment

Your email address will not be published. Required fields are marked *