If your existing array is potentially huge, maybe a binary search would be helpful. I implemented (a lame) one lately. I say lame because it does only eq and lt comparisons.

I keep meaning to rewrite this more like sort to take a comparison coderef.

But anyway, the code:

#! /usr/bin/perl -w use strict; { # Need integer division here. use integer; # Determine if a string exists in a sorted list of strings # using a binary search # Fail to send a sorted list to this sub at your own peril sub listContains($$) { my ($list, $word) = @_; my $min = 0; my $max = $#$list; my $i = ($max - $min) / 2; my $done = 0; while (!$done) { my $current = $list->[$i]; # Found it, return true return 1 if ($word eq $current); # Cut off half of the remaining list ($word lt $current) ? $max = $i : $min = $i; my $newi = $min + (($max - $min) / 2); # Out of list words to try $done = 1 if($newi == $i); $i = $newi; } # If we got here, the word was not found, return false return 0; } } # unsorted list my @words = qw{ icebox jakfruit kelvin liquid effluvia fenestrate ghoul hufflepuff yurt zoroastrian magnanamous necrosis ocular porridge albatross bolognese catharsis denigrate unresponsive versimilitude wrangler xenophobic quayside runcible seriatim tangential }; @words = sort @words; my $word = shift; print "$word: " . listContains(\@words, $word) . "$/";

In reply to Re: Adding Unique Elements to Array by dmorelli
in thread Adding Unique Elements to Array by thekestrel

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.