In Perl, srand () provides the random number seed for rand (). Rand () generates the random number generator.
If srand () is not called before rand () is called for the first time, the system automatically calls srand () for you ().
Calling srand () with the same number of seeds will generate the same random number sequence.
Example:
CopyCode The Code is as follows: srand (26 );
$ Number1 = rand (100 );
Print "$ number1 \ n ";
Srand (26 );
$ Number2 = rand (100 );
Print "$ number2 \ n ";
The result is as follows:
F: \> Perl \ A. pl
0.3753662109375
0.3753662109375
If we remove the second srand (26), as follows:
Copy code The Code is as follows: srand (26 );
$ Number1 = rand (100 );
Print "$ number1 \ n ";
$ Number2 = rand (100 );
Print "$ number2 \ n ";
The result is as follows:
F: \> Perl \ A. pl
0.3753662109375
76.397705078125
F: \>
The two values are different.
With a smallProgramA sub-program is used to randomly output 20 random values. srand (Time | $) is used here, that is, each time srand is given a new seed, in this way, the random number is different. In the same way, the time function obtains the current time. Because the time is different, the seed is different and the random number we get is different.
Copy code The 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;
}
We will explain the functions of time:
Print "Time () =". Time (). "\ n"; # number of seconds from January 1, 1970 to the present
Print "localtime () =". localtime (). "\ n"; # current time
Print "gmtime () =". gmtime (). "\ n"; # standard Greenwich Mean Time
The output result is as follows:
F: \> Perl \ A. pl
Time () = 1350309421
Localtime () = mon Oct 15 21:57:01 2012
Gmtime () = mon Oct 13:57:01 2012
F: \>