An array is just a list of things indexed by sequential numbers. A hash is an "associative array"; an unordered list of things indexed by keys that are each associated with one of the things. Just as an array's indices are 'unique' (you can't have two elements names 33, for example), a hash's keys are also unique (you can't have two hash keys both named 'pete'). Hash elements aren't inherently ordered. That means that there isn't any concept of 'pete comes before dave'.

So use an array anytime you need an ordered list, or a list of things indexed numerically starting at zero. Use an array if you need to push, pop, shift, or unshift.

Use a hash anytime you need to organize a bunch of things indexed by keys instead of '0 .. n' subscripts. Use a hash where order is unimportant (or where you don't mind sorting the keys, or maintaining a sorted array of keys). Use a hash if you need to maintain uniqueness of keys. Use a hash for sparse arrays, if it makes sense to do so. Use a hash if you need to quickly verify existance of an item based on its key (exists).

There are an infinite number of uses for each.


Dave


In reply to Re: What defines the choice of a Hash or an Array? by davido
in thread What defines the choice of a Hash or an Array? by ghenry

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.