in reply to Given ref to hash value, retrieve the key

gazpacho,
What you are asking for isn't what you are asking for ;-)

You want a reference, which is small, light weight, and can easily be thrown around to yield a hash key when used one way and yield that specific hash key's value used a different way.

As has been stated, this can't be done the way you are trying to do it, but you could do it with a closure. This would work - but it would be nasty (not elegant) looking code. It won't provide the efficiency of just the ref to the value, but it is extremely fast in comparison to iteration and it allows for duplicate values unlike a reverse hash. Here it is:

#!/usr/bin/perl -w use strict; my %hash = ('first_key' => 1 , 'second_key' => 2); my $magic_ref = Create_Magic(\$hash{'second_key'},'second_key'); print "My value is ", ${&$magic_ref} , "\n"; print "My key is ", &$magic_ref('key') , "\n"; sub Create_Magic { my ($value, $key) = @_; return sub { if ($_[0] && $_[0] eq 'key') { return $key; } $value; } }

This creates a reference that yields the key when used one way and the value when used another way. The important thing here is that it is a code reference not a scalar reference. As other monks and I have already stated, doing it the way you wanted to isn't possible.

Cheers - L~R