Okay, this is NOT production ready, or even sane for that matter, but I couldn't resist. I call it: "hashes2hashes.pl". The script creates a hash of key=>value pairs from the __DATA__. While it is adding to the hash, it creates an array of references to the data. It then uses the references as keys to another hash which stores the $key of the first hash as the data element. Now if you have a reference to a value in %hash1 you can use it to look up the corresponding key stored in %hash2.
#!/usr/bin/perl use Data::Dumper; while(<DATA>){ chomp; ($key,$val)=split/=/; #add key => value pair to %hash1 $hash1{$key}=$val; #add reference to $hash1{$key} to @refs push @refs,\$hash1{$key}; #create second %hash that stores the reference as a key and $key as th +e value $hash2{\$hash1{$key}}=$key; } #Now let's see how we can reference the various things. print "Reference \$refs[0] is the value $refs[0] and points to: ${$ref +s[0]}\n"; print "In \$hash2, $refs[0] points to the value $hash2{$refs[0]}\n"; print "The key $hash2{$refs[0]} can be then used to reference \$hash1{ +\$hash2{\$refs[0]}} => $hash1{$hash2{$refs[0]}}\n"; # And some Dumper output to make sure it looks good. print Dumper(\%hash1, \@refs, \%hash2); __DATA__ key1=1 key2=2 key3=3 OUTPUT: Reference $refs[0] is the value SCALAR(0x804c05c) and points to: 1 In $hash2, SCALAR(0x804c05c) points to the value key1 The key key1 can be then used to reference $hash1{$hash2{$refs[0]}} => + 1 $VAR1 = { 'key2' => '2', 'key1' => '1', 'key3' => '3' }; $VAR2 = [ \$VAR1->{'key1'}, \$VAR1->{'key2'}, \$VAR1->{'key3'} ]; $VAR3 = { 'SCALAR(0x804c05c)' => 'key1', 'SCALAR(0x804c194)' => 'key3', 'SCALAR(0x804c140)' => 'key2' };
I remember reading that using references as hash keys was bad. Maybe someone who knows a little more perl internals can tell me if the references would ever change during my program(provided I don't copy %hash1 of course)? Or if there is some other horrid reason not to do things this way?
In reply to Re: Given ref to hash value, retrieve the key
by pzbagel
in thread Given ref to hash value, retrieve the key
by gazpacho
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |