in reply to removing repeated elements from one array

From perlfaq4:

Use a hash. When you think the words "unique" or "duplicated", think "hash keys". If you don't care about the order of the elements, you could just create the hash then extract the keys. It's not important how you create that hash: just that you use keys to get the unique elements.

my %hash = map { $_, 1 } @array; # or a hash slice: @hash{ @array } = (); # or a foreach: $hash{$_} = 1 foreach ( @array ); my @unique = keys %hash;

(This is also cited in perlmonks Q&A here).

--------------------------------------------------------------

"If there is such a phenomenon as absolute evil, it consists in treating another human being as a thing."

John Brunner, "The Shockwave Rider".

Replies are listed 'Best First'.
Re^2: removing repeated elements from one array
by Akhasha (Scribe) on Nov 14, 2005 at 04:22 UTC
    Note that this works only for scalars (good enough for most purposes) - if its a list of object references and you want duplicates removed:
    my %hash = map { $_ => $_ } @array; # then... my @unique_unordered = values %hash; my @unique_ordered = grep {defined} map { delete $hash{$_} } @array;
    And for this to make sense the array elements must all be references to objects - if some elements are strings its possible for them to be equal to and overwrite a stringified reference.
A reply falls below the community's threshold of quality. You may see it by logging in.