I actually wrote 2 of my own. Neither use a hash, but I'm really impressed with the first one that uses only one line. Anyway, here are both of mine:
sub unique1 { for ($i=$#_;$i>=0;$i--){ my @rest = @_; my $test = splice(@rest,$i,1); if (grep($_ eq $_[$i],@rest)){@_ = @rest}; } return @_; } sub unique2 { foreach $test (@_){ my $i = -1; @indexes = map {$i++;$_ eq $test ? $i : ()} @_; shift @indexes; foreach $index (@indexes){ splice(@_,$index,1); } } return @_; }
The second one works by removing all the things that are duplicates. The second one works by not adding things that are duplicates. Depending on your array, one might be better than the other.

An important thing to remember is that when you make a unique array, you might want to preserve the order. Both of mine do, and so does the original one. Using keys with a hash does not preserve order.


In reply to RE: Return a Unique Array by Anonymous Monk
in thread Return a Unique Array 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.