I have a collection of items. They must be accessible by key (which says hash), but also by position (which says array).
This begins to sound like an Tie::( DxHash/IxHash/InsertOrderedHash ), but it's not.
I need to be able to:
- re-order the items in the array, but retain the keyed access from the hash.
- alter an items position in the array, having located it by key.
- discover the items key, having located it through array indices.
hash array
+---+---+ +---+
| A | | -\ /---> | | 0
+---+---+ \ / +---+
| B | | ---/-\ /-> | | 1
+---+---+ / \ \ +---+
| C | | -/ / \-> | | 2
+---+---+ / \ +---+
| D | | -\ / \-> | | 3
+---+---+ \ +---+
| E | | -/ \-----> | | 4
+---+---+ +---+
If I use the indices for the array elements as the values of the hash, I fail requirement 1).
If I use references to the array elements as the values of the hash, 1) is satisfied but 2) & 3) aren't.
If I store the data as the value in the hash, and put a copy of the key in the array, then I satisfy 1) & 3), but not 2).
So my question is: Is there some method method of satisfying all 3 requirements without resorting to a linear search of either the array or the hash values?
It feels as though one extra level of indirection is required, but I can't see where to put it.
If it makes a difference, the items themselves are already references to arrays containing several items, and I'd prefer to avoid to many further levels of indirection.
Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
"Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon
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.