in reply to auto-magical flipped hashes

The previous comment shows a good way to do this, but hashes with duplicate values would present a problem. %hash = ('a' => 1, 'b' => 1, ); Would you want to eliminiate one of the keys %flipped = ('1' => 'b'); or would you want them converted to a more complex structure? %flipped = ('1' => 'a', 'b');

Replies are listed 'Best First'.
RE: RE: auto-magical flipped hashes
by perlmonkey (Hermit) on Jul 13, 2000 at 07:56 UTC
    Very good point. This (not very optimised) code would flip and create the data structure. It is a bit cheesy though:
    use Data::Dumper; my %hash = ( 'a'=>1, 'b'=>2, 'c'=>3, 'd'=>4, 'e'=>4, 'f'=>4); my %by_value = flip(%hash); print Data::Dumper->Dump([\%hash], ['*hash']); print Data::Dumper->Dump([\%by_value], ['*by_value']); sub flip { my($k, $v, %hash); my %foo = @_; $hash{$v} = defined $hash{$v} ? [ ref $hash{$v} ? @{$hash{$v}} : $hash{$v} , $k ] +: $k while (($k,$v) = each %foo); return %hash; }
    Results:
    %hash = ( 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 4, 'f' => 4 ); %by_value = ( 1 => 'a', 2 => 'b', 3 => 'c', 4 => [ 'd', 'e', 'f' ] );