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

I want to get an array which has all the element unified, like (@array=(a,b,c,d,e,f)is OK; if @array=(a,b,c,a)because it already has an 'a' inside the array, I will keep it to @array=(a,b,c);. ....... my code like:
my @array=split('',$_); my $data=$array[2]; push(@data, $data);
I have to check if $data is already inside @data before I push it in. What should I do? Thanks!!!

Replies are listed 'Best First'.
Re: check element if inside an array
by Abigail-II (Bishop) on Apr 24, 2003 at 15:04 UTC
    That's a FAQ. To filter out duplicates, use something like:
    my %seen; @data = grep {!$seen {$_} ++} @data;

    Abigail

Re: check element if inside an array
by broquaint (Abbot) on Apr 24, 2003 at 15:06 UTC
    If you want uniqueness then just use the keys of a hash
    my %hash = map { $_ => 1 } 'a' .. 'f'; $hash{b} = 'added' unless exists $hash{b}; $hash{g} = 1 unless exists $hash{g}; print %hash; __output__ e1f1g1a1b1c1d1

    HTH

    _________
    broquaint

Re: check element if inside an array
by ctilmes (Vicar) on Apr 24, 2003 at 15:07 UTC
    When you are doing things like this, you should consider using a hash instead of an array:
    my %hash = map { $_ => undef } @array; # Add things to hash like this: $hash{'a'} = undef; $hash{'d'} = undef; # Turn back into list with 'keys' print join(',', sort keys %hash), "\n";