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

hi i have a data set with various terms....and i want to build a list with the index of terms (actually i want to delete the repeated terms..) i use this code:
foreach $term (@TERMS){ push(@INDEX,$term); for($i=0; $i<scalar(@TERMS); $i++){ if ($term eq $TERMS[$i]){ delete $TERMS[$i]; } } }
the code above delete the values of the repeated terms but it leaves the position blank ($TERMS[$i]), i want to delete the position too...how can i do that?

Replies are listed 'Best First'.
Re: delete an element from an array
by FunkyMonk (Bishop) on Apr 07, 2008 at 18:52 UTC
    splice will do as you ask, but if all you want to do is get a list of unique items in the array, see "How can I remove duplicate elements from a list or array?" in perlfaq4

Re: delete an element from an array
by kyle (Abbot) on Apr 07, 2008 at 18:57 UTC

    To answer the question asked, you can use splice.

    That having been said, what you really want is to keep a list of unique terms. You can do that this way:

    my %term_hash = map { $_ => 1 } @TERMS; my @INDEX = keys %term_hash;

    This differs from what you're doing mainly in that the @INDEX you get is not in any particular order.

    See also How can I extract just the unique elements of an array?

Re: delete an element from an array
by runrig (Abbot) on Apr 07, 2008 at 19:00 UTC
    You'd be deleting every element of @TERMS if that code worked. You can delete array elements with splice, but it would be easier to use a hash to keep track of duplicates:
    my %seen; @TERMS = grep { ! $seen{$_}++ } @TERMS;
    Updated...fixed due to catch from johngg.
Re: delete an element from an array
by dwm042 (Priest) on Apr 07, 2008 at 20:52 UTC
    This is a "one liner" with List::MoreUtils. Turning it into an example program:

    #!/usr/bin/perl use warnings; use strict; use List::MoreUtils qw/ uniq /; my @TERMS = ( 1,2,7,2,4,5,3,4,2,2,4,27,81,3 ); my @INDEX = uniq @TERMS; print "(", join( ',',@INDEX), ")\n";
    And the output is:

    C:\Code>perl uniqarray.pl (1,2,7,4,5,3,27,81)