Hello Monks:
Here is an interesting case I don't see covered in Perldoc. I thought about changing my data structure so it doesn't happen, but wanted to post it here first in hopes of attaining Wisdom and sharing a fun puzzle. Apologies if I'm missing something in the FAQ.
I start with a reference to a hash value and want to get at its key. Suppose that I start with a basic hash:
%The_Hash = (
"first_key" => 1,
"second_key" => 2
);
Now, I make a reference to one of the hash values:
$Ref_To_Hash_Value = \$The_Hash{"second_key"};
print ${$Ref_To_Hash_Value}; # prints 2
Given $Ref_To_Hash_Value, I now need to obtain the name of its key. In other words, I need the string "second_key".
Now the fun part . . . assume that %The_Hash will become very large, that it will be changing frequently, and that we'll create lots and lots of references to its values. We'll also want to do this key lookup quite often. We _could_ iterate over the whole hash using keys() or reverse(), but that would require traversing the whole darn hash every time we want to find a key. That could get pretty slow. It seems to me that, given a reference to the value of the key/value pair, we should be able to pull some sort of syntax magic to get the key.
Here are two ideas, neither of which I know how to implement:
* Decrement the internal pointer of the hash, since the key should be the element before the value, right?
* Start with a reference to the key rather than the value, then deref it to retrieve the string.
Thanks in advance for any Wisdom you might be able to offer.
Gazpacho (Initiate, but learning)
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.