Usage of srand () and time functions in Perl

Source: Internet
Author: User

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: \>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.