Sinister variable caching problem with rand()

Anthony Esposito <[email protected]>
Newsgroups gmane.comp.apache.mod-perl
Message-ID <[email protected]>
In one of my programs I started to receive database errors for not having a
unique id. I generate unique ids for each of the mysql lines that I add to
the database. I realized that the perl variable $idNum was keeping the same
random string for multiple executions.

I created a test program to demonstrate the principle of what is happening.

I have shown that the $count variable will function properly, I understand
why and expect $idNum to work the same way. However, when $idNum =
rand(99999999999) is used it misbehaves and starts to show the same numbers
after enough refreshes.

The code stores the random numbers in a file so I can detect them over
multiple sessions. Within the same session a random key has never been
generated twice.

Please help, I have been working on this for 2 days and it is killing my
progress at work.

-------------------------------------------------------------------------

use strict;

my $idNum=0;
my $count=0;
for(1..10){
my %hash;
open(data,"<keys.txt");
while(<data>){
chomp;
$hash{$_}=$_;
}
close(data);

$idNum = rand(9999999999999);
$count++;
open(data2,">>keys.txt");
print data2 "$idNum\n";
close(data2);

if ($hash{$idNum}){ print "DUPLICATE - $idNum<br>\n";}else{ print "UNIQUE
$idNum<br>\n"; }

}

print "$count";
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.