davidos code is way more elegant, if you employ matijas fix, but since I wrote it, here is a rather ugly solution:

my %hash2 = (); my %unique = (); foreach my $test (grep(!$unique{$_}++, values %hash)) { $hash2{$test} .= join(",", grep({$hash{$_} eq $test ? hash{$_} : u +ndef} keys %hash)); }

And since I was wondering, it isn't slower than davidos solution, the solutions seem to be equally efficient:

use strict; use warnings; use Data::XDumper qw(Dump); use Benchmark qw(:all); my %hash = ( ball1 => 'red', ball2 => 'blue', ball3 => 'red', ); print scalar Dump(\%hash); my %hash2 = (); my %unique = (); my %reverse_hash; cmpthese(1000000, { 'unique_grep' => sub { %unique = (); %hash2 = (); foreach my $test (grep(!$unique{$_}++, values %hash)) +{ $hash2{$test} .= join(",", grep({$hash{$_} eq $tes +t ? $hash{$_} : undef} keys %hash)); } }, 'reverse_hash' => sub { %reverse_hash = (); while ( my ( $key, $value ) = each %hash ) { push @{$reverse_hash{$value}}, $key; } }, }); __END__ 1st run: Rate unique_grep reverse_hash unique_grep 29940/s -- -2% reverse_hash 30694/s 3% -- 2nd run: Rate reverse_hash unique_grep reverse_hash 28466/s -- -2% unique_grep 29104/s 2% --

regards,
tomte


Hlade's Law:

If you have a difficult task, give it to a lazy person --
they will find an easier way to do it.


In reply to Re: mildly tricky hash question by Tomte
in thread mildly tricky hash question 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.