If the order in which you are populating the array is important, then populate both an array and an %already_seen hash (don't populate the array if the element exists in the hash). This will be much faster than greping your array each time.

If the order of insertion is not important, then don't use an array, use only a hash, you are guaranteed against duplicates. You can still sort your hash on keys.

Well, if the order is important, you might still use only a hash, with the elements as keys, and the order of insertion as values. At then end, you only need to sort the hash on the values. This will probably not be faster than populating both an array and a hash, but if speed is not crucial (no huge data set), the code will be a bit simpler.


In reply to Re: Checking if an item exists in an array before adding a record to it. by Laurent_R
in thread Checking if an item exists in an array before adding a record to it. by viffer

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.