in reply to Return a Unique Array
The second one works by removing all the things that are duplicates. The second one works by not adding things that are duplicates. Depending on your array, one might be better than the other.sub unique1 { for ($i=$#_;$i>=0;$i--){ my @rest = @_; my $test = splice(@rest,$i,1); if (grep($_ eq $_[$i],@rest)){@_ = @rest}; } return @_; } sub unique2 { foreach $test (@_){ my $i = -1; @indexes = map {$i++;$_ eq $test ? $i : ()} @_; shift @indexes; foreach $index (@indexes){ splice(@_,$index,1); } } return @_; }
An important thing to remember is that when you make a unique array, you might want to preserve the order. Both of mine do, and so does the original one. Using keys with a hash does not preserve order.
|
|---|