Rand () is not so random in perl

I have a Perl script that gives me a string of 50 characters of random numbers, letters and some special characters. I entered them into the database. Now, given the length of the string and the number of characters, I would not have thought that duplicates would be easily created.

Here's a great nugget of code that creates a line:

my $random_id='';
my @c = ( "A" .. "Z", "a" .. "z", 0 .. 9, qw(! @ $ % ^ & *) );
$random_id = join '', map $c[rand @c] , 1 .. 50;

It creates strings like:

C1Qt8L7E7QUD% lkxnh9yjZ2njF0iMj! 1o ^ 4DmTbVNhQB9% DKE @

The problem is that it will duplicate the exact line every time and for some time among the unique ones, and several times on some lines. And this is from 20 lines. This is strange. I can get around this and find a solution ... but it puzzles me a bit. I would like to know why. Does anyone have an idea?

+5
source share
3

srand, , .

http://perldoc.perl.org/functions/srand.html

:

doc atthe url, perl 5.004, . perl, .

+8
+3

For GOOD random numbers, consider using Math :: Random :: MT .

+3
source

All Articles