http://www.perlmonks.org?node_id=76296

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

How can I display a unique array if it contains some repeated elements

Originally posted as a Categorized Question.

• Comment on How can I display a unique array if it contains some repeated elements

Replies are listed 'Best First'.
Re: How can I display a unique array if it contains some repeated elements
by dvergin (Monsignor) on Apr 28, 2001 at 10:10 UTC
If you mean, "How can I display an array of the unique elements of an array that contains some repeated elements", this may serve your purpose:
```my @ary = qw(a b c d d e b d);
my %hsh;
undef @hsh{@ary};
my @ary2 = keys %hsh;
print "@ary2\n";
The key here is:  undef @hsh{@ary};  which is a hash slice. The hash slice is an lvalue (that is, it is assignable). The undef is associative for each element of the slice. The effect of this is to establish a key in the hash corresponding to each array element. Except that duplicate keys just write over each other. Each key has a corresponding value of undef. Then, on the next line we just extract the (now unique) keys into a new array.

This is fine for some cases, but it does not preserve the ordering of the elements in the array. The origial poster did not indicate if they cared. Anyway, as IO pointed out, the node How can I extract just the unique elements of an array? discusses several methods for dealing with this depending upon the data that you are dealing with.

-ben

Re: How can I display a unique array if it contains some repeated elements
by I0 (Priest) on Apr 28, 2001 at 09:56 UTC
Re: How can I display a unique array if it contains some repeated elements
by tadman (Prior) on Jun 07, 2002 at 20:31 UTC
There is a similar technique which is slightly faster (~5-7%) on larger lists:
```my %h;
grep { !\$h{\$_}++ } @list;
The answer by dvergin is actually about 50% faster for lists smaller than ~2000 items.
Re: How can I display a unique array if it contains some repeated elements
by nudge (Acolyte) on Jun 20, 2010 at 07:14 UTC
```use List::MoreUtils qw(uniq);

my @list = (1,1,2,3,3,4);
print join( ',', uniq(@list) );
Re: How can I display a unique array if it contains some repeated elements
by Anonymous Monk on Aug 14, 2003 at 21:39 UTC
a sub to get both unique and not:
```@array1 = (1,1,2,3,3,4);
#unique
print unique(@array1);

#not
print unique(\@array1);

sub unique{
my (%seen, \$array);
(\$array)=@_;
if(@\$array){return grep{\$seen{\$_} ++} @\$array;}
else{return grep{ ! \$seen{\$_} ++} @_;}
}