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

Getting Duplicate Values in Hash

Status
Not open for further replies.

TommyIndigo

Programmer
Sep 14, 2000
67
US
The snippet of code I'm pasting below is supposed to add a new record ONLY IF it doesn't already exists. For some reason, it is adding the record twice. Any ideas? I'm rather new to "hashes of hashes", so any advice would help. Somewhere in the "if" block is where I suspect the problem. Thanks!

Code:
#Add users to the global user list
my $UsersDataFilePath = "$ExaminedProjectPath/users/data.txt";

my $TempCGIObject;
my $UserID;
  
# Open the Document Data File in read mode
open(DATAFILE1, &quot;<$UsersDataFilePath&quot;);
# Instantiate a new CGI object for each record in the user data file and store object
# reference in a hash table keyed on the unique ID field
while (!eof(DATAFILE1))
 {
  $TempCGIObject = CGI->new(\*DATAFILE1);
  #Only add if user isn't already on this list
  $UserID=($TempCGIObject->param('UserID'));

  if (!defined($GlobalUserList{$UserID}))
  {
   $GlobalUserList{$UserID}=$UserID;
   $GlobalUserList{$UserID}{EmailAddress}=($TempCGIObject->param('EmailAddress'));
   $GlobalUserList{$UserID}{DomainName}	= ($TempCGIObject->param('DomainName'));
   $GlobalUserList{$UserID}{UserName} =	($TempCGIObject->param('UserName'));
   }#end if
 }#end while
  
# Close the data file
close(DATAFILE1);
 
Are you trimming the key to make sure that
&quot;elvis&quot; isn't determined to be the same as
&quot; elvis&quot; or
&quot;elvis &quot;

Try throwing an else to your if to record &quot;duplicates &quot;

--Just a thought
Paul
 
I think Paul is right on here. I would toss in a line

print &quot;:$UserID:\n&quot; ;

right after I assigned the UserID. This is just for debug but immediately shows you exactly what you are using as a key.

You can also use Data::Dumper on your final data structure to see where you are going wrong. Data::Dumper is a fantastic tool for this sort of debug.
 
Gday,

According to the perlfunc reference,
&quot;When used on a hash element, it tells you whether the value is defined, not whether the key exists in the hash. Use exists for the latter purpose.&quot;

So your checking line should read:
if (!exists($GlobalUserList{$UserID}))
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top