http://www.perlmonks.org?node_id=31549

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question: (hashes)

reversehash to accept a hash and return a hash where the roles of keys and vaalues are reversed. that is the key of the key of the input hash becomes the value of the output hash. if there are more than one keys in the input hash has the same value, they are connected by the symbol '|' in output

Originally posted as a Categorized Question.

  • Comment on how to use reversehash if there are more than one keys same

Replies are listed 'Best First'.
Re: how to use reversehash if there are more than one keys same
by indigo (Scribe) on Sep 09, 2000 at 01:42 UTC
    Assuming the keys of your input hash cannot contain the '|' character. Straight forward:
    sub reversehash { my $href = shift; my %h; for (keys %$href) { my $v = $href->{$_}; if (exists $h{$v}) { $h{$v} .= "|$_"; } else { $h{$v} = $_; } } return \%h; }
    To impress the chicks:
    sub reversehash { my %h; push @{$h{$_[0]->{$_}}}, $_ for keys %{$_[0]}; $h{$_} = join '|', @{$h{$_}} for keys %h; return \%h; }