Re: Sinister variable caching problem with rand()
André Warnier <[email protected]>
| Newsgroups | gmane.comp.apache.mod-perl |
|---|---|
| Message-ID | <[email protected]> |
Adam Prime wrote: > Perrin Harkins wrote: >> On Sat, May 15, 2010 at 4:03 PM, Anthony Esposito >> <[email protected]> wrote: >>> 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. >> >> You need to call srand() in s a child init handler: >> http://marc.info/?l=apache-modperl&m=123904225030744&w=1 >> >> However, I have to ask, why are you generating id numbers randomly? >> Why not just let mysql do it with auto_increment? >> >> - Perrin > > I think, in theory you shouldn't have to explicitly srand yourself in > your startup.pl if you're using mod_perl 1.29 or greater, and perl 5.8.1 > or greater. > > see: > > http://marc.info/?l=apache-modperl-dev&m=106606815110220&w=2 > Also see : perldoc -f srand and http://en.wikipedia.org/wiki/Murphy%27s_law With the second, I mean that even if the rand() sequence is different in different Apache children and cgi-bin's or modules called by these children, that still does not mean that the same number could not be generated occasionally. Especially if this over a long period of time, and the result is stored in a database. So I would either use what Perrin mentioned, or combine the result of (a shorter) rand() call, with time() for example. A tip : to get a really unique identifier, I often use "yyyymmddhhmmssrrrrr", where rrrrr is the rand() result, and the prefix is the date/time. Unless you process more than 99,999 requests per second, it will always be unique. In addition, such an identifier is at the same time a time stamp, which is often invaluable in tracking down a problem.