[Israel.pm] exists item in array

Oron Peled oron at actcom.co.il
Mon Oct 8 14:11:02 PDT 2007


On Monday, 8 בOctober 2007, Ernst, Yehuda wrote:
> I want to enter items to array only if they does not exits there
> (i need 1 item of each type) 
> if i have     a b c d d d c
> the array will have
> a b c d

That was one of my favorites when I was teaching perl.

Several alternative solutions (with different conditions):

  @in = ('a', 'c', 'c', 'd', 'd', 'd', 'c');

1. Assume sorted items (your example), preserve order:

  my $prev = 'nosuchvalue';
  @out = grep($_ ne $prev && ((($prev) = $_),1), @in);

2. Any order input, preserve order:

  undef %saw;
  @out = grep(!$saw{$_}++, @in);

3. Any order input, does not preserve order:

  undef %a;
  @a{@in} = ();
  @out = keys(%a);

4. Any order input, @in contains (not very large) numbers,
   does not preserve order:

  @a[@in] = @in;
  @out = sort @a;

Have fun,

-- 
Oron Peled                             Voice/Fax: +972-4-8228492
oron at actcom.co.il                  http://www.actcom.co.il/~oron
ICQ UIN: 16527398

"Beware of bugs in the above code;
 I have only proved it correct, not tried it."
                              -- Donald E. Knuth



More information about the Perl mailing list