in reply to Find common values in a hash and print the respective keys

Here's a technique to achieve this.

$ perl -Mstrict -Mwarnings -E ' my (%x, %y) = (a => 1, b => 2, c => 3, d => 1, e => 2, f => 1); push @{$y{$x{$_}}}, $_ for keys %x; say "$_: ", join ", ", @{$y{$_}} for keys %y; ' 1: a, d, f 2: b, e 3: c

I'll leave you to format the output however you want it.

Take note of the following excerpt from the keys documentation:

"The keys of a hash are returned in an apparently random order."

The output shown above was not modified to appear sorted! Here's two more runs also with unmodified output:

$ perl -Mstrict -Mwarnings -E ' my (%x, %y) = (a => 1, b => 2, c => 3, d => 1, e => 2, f => 1); push @{$y{$x{$_}}}, $_ for keys %x; say "$_: ", join ", ", @{$y{$_}} for keys %y; ' 2: e, b 1: d, a, f 3: c
$ perl -Mstrict -Mwarnings -E ' my (%x, %y) = (a => 1, b => 2, c => 3, d => 1, e => 2, f => 1); push @{$y{$x{$_}}}, $_ for keys %x; say "$_: ", join ", ", @{$y{$_}} for keys %y; ' 3: c 1: f, d, a 2: b, e

Update: As ++LanX points out (below), this may not be the clearest example. Here's, hopefully, a better one. This doesn't change the logic, just the clarity.

$ perl -Mstrict -Mwarnings -E ' my %orig = (a => 1, b => 2, c => 3, d => 1, e => 2, f => 1); my %temp; push @{$temp{$orig{$_}}}, $_ for keys %orig; say "$_: ", join ", ", @{$temp{$_}} for keys %temp; ' 1: a, d, f 3: c 2: b, e

-- Ken

Replies are listed 'Best First'.
Re^2: Find common values in a hash and print the respective keys
by LanX (Saint) on May 26, 2013 at 21:40 UTC
    Is this more golfing or obfuscation regarding %y ? =)

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

    Cheers Rolf

    ( addicted to the Perl Programming Language)

      While neither golfing nor obfuscation was intended, your point is well taken: I've updated my node.

      Thanks (and ++ when the Vote Fairy next visits).

      -- Ken