Perl uses the functions rand () and srand () to generate random numbers (more specifically, pseudo-random numbers. These functions do not use encryption to provide security, so do not use them to encrypt your financial information. However, if you need to design a simple random number generator for the new features of your next game or dynamic Web site, rand () and srand () may be what you need.
The rand () function is a real random number generator, and srand () sets the random number seed for rand. The rand () function returns a score between 0 and your specified number (1 by default. If you did not call srand () before calling rand () for the first time, the system will automatically call srand () for you ().
Note that calling srand () with the same number of seeds will generate the same random number sequence. This is sometimes very convenient, especially in game programming, you may want to repeat the random events according to the exact same sequence.
Use rand () as follows ():
Print "Your lucky number for today is:". int (rand (100) + 1 )."";
Command: rand
Syntax: rand ($ interger)
Note: This function is often used with the srand function to obtain a random number. If the stand function is not declared first, the constant value is a fixed value. This syntax returns a value between 0 and $ interger. If $ interger is omitted, a value between 0 and 1 is returned.
Example:
Srand; # The srand function must be declared before a random number is generated.
$ Int = rand (10); # $ the int value is greater than 0 and smaller than 10. If you want to generate a random number that is an integer, you must add int # This function.
$ Int = int (rand (10); # the value of $ int is an integer between 0 and 9.
---------
$ Int = rand (10 );
$ Int = int (rand (10 ));
Print "int is $ int \ n ";
Run:
Int is 9
Run again:
Int is 7
# The visible rand value is a random number.
Example: I have 7000 rows of text data. How can I randomly extract 1280 rows, extract 100 times, and finally generate 100 1280 lines of text? Please advise.
Copy codeThe Code is as follows :#! /Usr/bin/perl
Use strict;
Use warnings;
My $ data_file = "file1 ″;
Print "Generating... \ N ";
Open FH, "$ data_file" or die "Can not open the required file $ data_file! ";
My @ data = <FH>;
Close FH;
For (1. 100 ){
My % hash;
While (keys % hash) <1280 ){
$ Hash {int (rand ($ # data)} = 1;
}
Open OUT, "> random=_.txt" or die "Can not open the required file random=_.txt! ";
Foreach (keys % hash ){
Print OUT "$ data [$ _]";
}
Close OUT;
}
Print "Complete! \ 7 ″;