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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Eliminating duplicate entries in an array 1

Status
Not open for further replies.

nfaber

Technical User
Oct 22, 2001
446
US
What is an easy way to eliminate duplicate entries in an array? I am reading a file in that has as many as 19 duplicate entries, and I want to eliminate all but one of course. Here is an excert form my script:

open (PFZ, $outemp) or die ("could not open pfizer.tmp: $!");
open (OUT, ">file.txt") or die ("could not open output file: $!");


# split the file and perform extraction logic.

foreach $var1 (<PFZ>) {

my @fields = split ( /\t/, $var1);

foreach (@fields) {
next if ( $fields[3] !~ /$query/ );
print (OUT &quot;$fields[17],$fields[3],$fields[13],$fields[5]\n&quot;);
}
}


Any help is appriciated.
 
Well, if you place the file in an array called @file you could do the following:
my %entries;
foreach my $entry (@file)
{
$entries{$entry}++;
}
my @entries = keys (%entries); //Daniel
 
Daniel,

I kinda a newbie here, but I do not see how that eliminates duplicate entries. Can you explain?
 
%entries is a hash array - and keys to a hash array are two things, they can be a string (so they can store the values from an ordinary array) and they are unique.... Mike
michael.j.lacey@ntlworld.com
Email welcome if you're in a hurry or something -- but post in tek-tips as well please, and I will post my reply here as well.
 
Oh I see! A hash must have unique keys so by writing the array to a hash the duplicates will be eliminated automatically. How clever!
 
Mike,

How would you incorporate writing the array into a hash in the program show on my original post?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top