in reply to Adding Unique Elements to Array

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) . "$/";