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


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

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.

Replies are listed 'Best First'.
Re: Answer: How can I display a unique array if it contains some repeated elements
by knobunc (Pilgrim) on Apr 30, 2001 at 18:02 UTC

    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