Beefy Boxes and Bandwidth Generously Provided by pair Networks chromatic writing perl on a camel
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

RE: RE: auto-magical flipped hashes

by perlmonkey (Hermit)
on Jul 13, 2000 at 03:56 UTC ( [id://22316]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


in reply to RE: auto-magical flipped hashes
in thread auto-magical flipped hashes

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' ] );

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://22316]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.