ithron has asked for the wisdom of the Perl Monks concerning the following question:

Besides some convoluted foreach loop, is there a way to determine if an element is already in an array before adding said element to the array?
  • Comment on Determining if an element is already in an array.

Replies are listed 'Best First'.
RE: Determining if an element is already in an array.
by davorg (Chancellor) on Feb 02, 2000 at 01:17 UTC

    No need for a loop. Try this:

    my %check; @check{@arr) = (1) x @arr;

    You now have a hash %check which has a key/value pair for each element in the list. You can check for the existance of value, $val, by doing:

    if $check{$val}
Re: Determining if an element is already in an array.
by Anonymous Monk on Feb 02, 2000 at 00:04 UTC
    You can use the grep function: push(@foo,$elm) unless grep(/$elm/,@foo); Creating a hashtable every time you're tring to test for an element may be alot of overhead (memory and CPU).
Re: Determining if an element is already in an array.
by dlc (Acolyte) on Feb 01, 2000 at 21:45 UTC

    the foreach loop is not so convoluted. i spell if f-o-r here.

    my @foo = qw(1 4 g 7 h rf s 4 6 7 9); my %foo = (); $foo{$_}=$foo[$_] for @foo; @foo=keys %foo;

    @foo is your original list, and %foo is a temporary hash that you will use to hold the unique values (since every key in a hash is unique).

Re: Determining if an element is already in an array.
by Anonymous Monk on Feb 02, 2000 at 18:23 UTC
    I'm sort of new to this, so maybe this is just 'baby talk', but this has always worked for me: push @arr, $el if !$seen{$el}++; The hash value $seen{$el} is not incremented until after the test and so is always zero the first time through, non-zero thereafter.