Introduction to the use of Srand () and Time functions in Perl _ Application techniques

Source: Internet
Author: User
Tags rand

In Perl, Srand () provides random number seeds for use by rand (), and Rand () produces random number generators.
If Srand () is not invoked before the first call to Rand (), then the system automatically invokes Srand () for you.
Calling Srand () with the same number of identical numbers causes the same sequence of random numbers to be generated.

Examples are as follows:

Copy Code code as follows:

Srand (26);
$number 1=rand (100);
Print "$number 1\n";
Srand (26);
$number 2=rand (100);
Print "$number 2\n";

The results obtained are as follows:
f:\>perl\a.pl
0.3753662109375
0.3753662109375

If we remove the second Srand (26), the following:

Copy Code code as follows:

Srand (26);
$number 1=rand (100);
Print "$number 1\n";
$number 2=rand (100);
Print "$number 2\n";

The results obtained are as follows:
f:\>perl\a.pl
0.3753662109375
76.397705078125

F:\>

The resulting two values are different.

With a small program, the use of a subroutine, random output of 20 random values, used here, Srand (time|$$), that is, each time to give srand new seeds, so as to ensure that the random number is not the same, the same inside time function to obtain the current times, Because the time is different, so the seed is different, we get the random number is different.

Copy Code code 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 give a description of the various functions of time:
print ' time () = '. Time (). " \ n "; #从1970年到现在的秒数
Print "localtime () =". LocalTime (). \ n "; #当前时间
Print "gmtime () =". Gmtime (). \ n "; #标准格林威治时间

The output results are as follows:
f:\>perl\a.pl
Time () =1350309421
LocalTime () =mon Oct 15 21:57:01 2012
Gmtime () =mon Oct 15 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.