SoFunction
Updated on 2025-04-08

Introduction to the usage methods of srand and time in perl

In perl, srand() provides a random number seed for rand(), and rand() generates a random number generator.
If srand() is not called before the first call to rand(), the system will automatically call srand() for you.
Calling srand() with the same number as the same seed will cause the same random number sequence to be generated.

As an example:

Copy the codeThe code is as follows:

srand(26); 
$number1=rand(100); 
print "$number1\n"; 
srand(26); 
$number2=rand(100); 
print "$number2\n";

The results obtained are as follows:
F:\>perl\ 
0.3753662109375 
0.3753662109375

If we remove the second srand (26), as follows:

Copy the codeThe code is as follows:

srand(26); 
$number1=rand(100); 
print "$number1\n"; 
$number2=rand(100); 
print "$number2\n";

The results obtained are as follows:
F:\>perl\ 
0.3753662109375 
76.397705078125 

F:\>

The two values ​​generated in this way are different.

It comes with a small program, which uses a subroutine, randomly outputs 20 random values. Here, srand (time|$$), which means that srand is given a new seed every time, so that the random numbers obtained are different. In the same way, the time function gets the current time. Because the time is different, the seeds are different, and the random numbers we get are different.

Copy the codeThe code is as follows:

#!/usr/bin/perl
my $dna='AACCGTTAATGGGCATCGATGCTATGCGAGCT'; 
srand(time|$$); 
for (my $i=0;$i<20;++$i) 

    print randomposition($dna), " "; 

print "\n"; 
exit; 

sub randomposition 

   my($string)=@_; 
   return int rand length $string; 
}

Let's explain the various functions of time:
print "time()=".time()."\n";#Seconds from 1970 to the present
print "localtime()=".localtime()."\n";#Current time
print "gmtime()=".gmtime()."\n";#Standard Greenwich Time

The output result is as follows:
F:\>perl\ 
time()=1350309421 
localtime()=Mon Oct 15 21:57:01 2012 
gmtime()=Mon Oct 15 13:57:01 2012 

F:\>