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


In reply to Re: Given ref to hash value, retrieve the key by Limbic~Region
in thread Given ref to hash value, retrieve the key by gazpacho

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.