Perl uses the functions rand () and srand () to provide basic tools for generating random (or rather, "pseudo-random") strings. 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 your next game or new feature of a dynamic Web site, then rand () and srand () may be all you need.
The function rand () is a true random number generator, and srand () sets a random number seed for rand (). The function rand () returns a score between 0 and the number you specify (the default is 1). If you don't call srand () before the first call to rand (), the system will automatically call srand () for you.
Note that calling srand () with the same number as the seed will cause the same sequence of random numbers to be generated. This is sometimes convenient, especially in game programming, where you may want to repeat random events in exactly the same sequence.
Use rand () like this:
print "Your lucky number for today is:". int (rand (100) + 1). "";
Instruction: rand
Syntax: rand ($ interger)
Explanation: It is often used with the function srand to obtain a random number. If the stand function is not declared first, the constant value taken out is a fixed value. This syntax returns a value between 0 and $ interger. If $ interger is omitted, it returns a value between 0 and 1.
Example:
srand; #The srand function must be declared before it can produce a random number effect
$ int = rand (10); #The value of $ int will be greater than 0 and less than 10. If you want the random number to be an integer, add int #
$ int = int (rand (10)); # $ int is an integer with a value 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
#Visible rand takes random numbers
Example: I have 7000 lines of text data. I want to randomly extract 1280 lines from it, extract 100 times, and finally generate 100 1280 lines of text. What should I do? Please give pointers.
Copy the code:
#! / 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 ″;