<?xml version="1.0" encoding="windows-1252"?>
<node id="580201" title="rand / srand" created="2006-10-24 03:17:55" updated="2006-10-23 23:17:55">
<type id="115">
perlquestion</type>
<author id="417993">
jbrugger</author>
<data>
<field name="doctext">
&lt;p&gt;Dear monks&lt;/p&gt;

I need your help again.&lt;br&gt;
For a tracking number, i generate random keys, with a length of 8 characters.
The code i use is the following:&lt;br&gt;&lt;br&gt;

&lt;c&gt;
# srand();  # Generates collisions (no true random codes, also tried at the beginning of the code (not in the sub)
# srand(time); # Generates collisions (no true random codes)

sub GenCode {
	my $args = {
		AvailableChars	=&gt; "ACDEFHIJKLMNPQRTUVWXYZ234679",
		CodeLength	=&gt; 8,
		@_,
	};
	# srand();  # Generates collisions (no true random codes, also tried at the beginning of the code (not in the sub)
	# srand(time); # Generates collisions (no true random codes)
	srand (time ^ $$ ^ unpack "%L*", `ps axww | gzip`); #seems to work, but is slow.
	my $rndcode = '';
	my @AvailableCharsA = split "", $args-&gt;{AvailableChars};
	for (my $j=0;$j&lt;$args-&gt;{CodeLength};$j++) {
		$rndcode .= $AvailableCharsA[int(rand(@AvailableCharsA-1))];
	}
	return $rndcode;
}
&lt;/c&gt;

The problem is the following:&lt;Br&gt;
If i use srand at the beginning of the module, it will create the same keys after some time again.&lt;Br&gt;
If i use srand(time), this also happens, so i've put it in the sub Gencode.&lt;Br&gt;
As the documentation of srand says, i should not do this, and next, the same keys were generated after some time again.&lt;Br&gt;
I searched Pelmonks, google, and came up with the above solution, using &lt;c&gt;srand (time ^ $$ ^ unpack "%L*", `ps axww | gzip`);&lt;/c&gt;&lt;br&gt;

This is 'slow', and i wonder why (mod) perl does not genterate true random codes, in the above code there should be enough space to generate lots of different keys without having collisions.&lt;br&gt;&lt;br&gt;

So the question is, how do i properly create random keys as described above&lt;BR&gt;&lt;br&gt;

&lt;b&gt;update&lt;/b&gt;&lt;br&gt;
Thanks for all your help, i'll have to look into one of the solutions.&lt;br&gt;
The thing (i think!) makes it difficult, is the fact that we preload all our modules into apache.&lt;br&gt;
If the process is started and srand is called, i think the child process of apache uses the same seed (please correct me if i'm wrong here), thus generates the same random keys again.&lt;br&gt;&lt;Br&gt; 

&lt;!-- Node text goes above. Div tags should contain sig only --&gt;
&lt;div class="pmsig"&gt;&lt;div class="pmsig-417993"&gt;
&lt;small&gt;"We all agree on the necessity of compromise. We just can't agree on when it's necessary to compromise." - Larry Wall.&lt;/small&gt;
&lt;/div&gt;&lt;/div&gt;</field>
</data>
</node>
