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


In reply to Re: Find common values in a hash and print the respective keys by kcott
in thread Find common values in a hash and print the respective keys by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.