Are you using a hash because you want efficient lookups of individual keys? Because you want to assure uniqueness of keys? Or simply because you want to express key=>value relationships?

If your primary interests are key/value relationships and insert order, you may not need a hash so much as a List of Lists, as in:

my @array = ( [ 'snake' => 1 ], [ 'dog ' => 2 ], [ 'zebra' => 3 ], ); print "$_->[0], " for @array;

Hashes by nature are not "ordered" in any meaningful way. If you need to preserve the O(1) lookups of hash elements, while also preserving some sort of order, you could keep track of key insertions in one array, and the key/values in a hash. Essentially the array is an ordered index of hash keys that way.

The tie approach creates tie overhead for every access. That may not be much of an issue, but it is there.

The LoL approach described at the top of my post assumes that you don't care about O(1) lookups at all, and just care about relationships and order.

Different approaches depending on what you really need to do. ....what do you need to do, anyway?


Dave


In reply to Re: Specify Output of Keys in Hash by davido
in thread Specify Output of Keys in Hash by Anonymous Monk

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.