Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Removing Duplicates In An Array

Status
Not open for further replies.

bretttt

Programmer
Jul 23, 2002
74
US
Hello, I have an array which contains

example: 1,3,5,7,5,3,9,10,11,12

how can i remove any duplicates such as the threes and fives?

if (@array){
foreach(@array){
}
}

thanks
 
sub remove_duplicates {
my @array = @_;

# Remove duplicates
my %temp_hash;
$temp_hash{$_} = 1 for (@array);
my @new_array = ();
push @new_array, $_ for (keys %temp_hash);

return @new_array;
}

M. Brooks
X Concepts LLC
 
Same idea, but shorter done with a map:
Code:
my @array = (1,3,5,7,5,3,9,10,11,12);

my %hash = map {$_ => 1} @array;

my @uniq = keys %hash;

________________________________________
Andrew - Perl Monkey
 
I like the perl cookbook method:

Code:
my @array = (1,3,5,7,5,3,9,10,11,12);
my %seen;

@uniq = grep { ! $seen{$_}++ } @array;
 
(one problem with the other two methods shown, by the way, is that order of the original array is lost.)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top