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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |