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

Preventing duplicate array values 2

Status
Not open for further replies.

torstens

Technical User
Oct 9, 2006
26
US
I'm taking in search values to make up a file system. When I take the $search in I want to add that to an array. The problem is when I want to only add it if it is not already present. Right now it just keeps on adding it to the array rather than only if it is new. Any help is appreciated.


unless (@AJmasterNAMES =~ /$AJsearch/g) {
push @AJmasterNAMES, "$AJsearch\n";
print AJMASTERNAMES "@AJmasterNAMES";
}
 
my %hash = ();

unless (@AJmasterNAMES =~ /$AJsearch/g) {
$hash{$AJsearch} = 1;
print join("\n", keys %hash);
}
print "\n";
 
I'm quite new to this, and am hoping for a little explanation. I'm trying to get the final (duplicate free) array and then print it into a text file. I tried altering your code just a bit, but it still throws in the duplicates.

my %hash = ();
unless (@AJmasterNAMES =~ /$AJsearch/g) {
$hash{$AJsearch} = 1;
@AJmasterNAMES = join("\n", keys %hash);
print AJMASTERNAMES "@AJmasterNAMES";
}
print "\n";
 
My bad. I did not really notice line this before:

unless (@AJmasterNAMES =~ /$AJsearch/g) {

Your code should go as follows:

my %hash = ();

# $item will contain each item from the array in turn
foreach my $item (@AJmasterNAMES){
#skip items that do not match
next unless ($item =~ /$AJsearch/g) {

#A hash cannot have duplicate keys
$hash{$item} = 1;
}

#Only need to do this once.
@AJmasterNAMES = join("\n", keys %hash);
print AJMASTERNAMES "@AJmasterNAMES";
print "\n";


 
you could just use a hash to begin with:

Code:
$AJmasterNAMES{$AJsearch}=$AJsearch;

hash keys must be unique, so you never get a duplicate if you use the term you don't want duplicated as a key for the hash. You could then reduce that to an array of you wanted to:

Code:
@AJmasterNAMES = sort {lc{$a} cmp lc($b)} keys %ALmasterNAMES;


But if you want to stick with the array you can get rid of duplicates after the array is completed instead of checking the array each time a new element is added. So you can do this to begin with:

Code:
push @AJmasterNAMES, $AJsearch;

until you no longer need to add more stuff to the array or until you need to check it for duplicates. Then get rid of the duplicates:

Code:
my %seen = ();
@AJmasterNAMES = grep {!$seen{$_}++} @AJmasterNAMES;
%seen = (); # empty the hash in case you need to use it again

- Kevin, perl coder unexceptional!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top