Some parts of this page were machine translated.
Powered by Yandex.Translate
http://translate.yandex.com/
Na linguagem de programação Perl possui a função de srand()
.
srand()
em Perl
Na linguagem de programação Perl possui a função de srand()
.
Esta função é utilizada para instalar ou para obter o número de
seqüência de valores numéricos a partir do qual obtém a função de rand()
.
A função mais comum srand()
é usado em testes para sempre
o teste a função de rand()
produza os mesmos valores.
Aqui está um exemplo de código:
#!/usr/bin/perl
use strict;
use warnings;
use feature qw(say);
srand(16);
say int(rand(10));
say int(rand(10));
say int(rand(10));
say int(rand(10));
say int(rand(10));
O resultado do programa é sempre as mesmas 5 dígitos:
1
0
9
3
3
O programa usa int(rand(10))
para obter um número aleatório de 0
(inclusive),
até 9
(inclusive).
No código há uma chamada srand(16);
. Esta chamada define o que a função rand()
deve retornar
os números pseudo-aleatórios de número de seqüência 16
. Cada um, portanto, a execução deste programa leva
para o mesmo efeito. Se este programa não foi chamada de função srand()
, o
diferentes execuções do programa podem retornar valores diferentes.
A função srand()
pode ser usado sem argumentos, ou passar exatamente um argumento.
No caso de se passar mais de um argumento, então o erro será:
Too many arguments for srand at script.pl line 3, near "2)"
Execution of script.pl aborted due to compilation errors.
Recurso não utiliza a variável de $_
.
Se houver a necessidade de usá-lo, você precisa ser explicitamente para a função de srand($_);
.
A função espera receber um número como o valor do argumento. Se a função não recebe número, então ela o leva a um número.
A função trunca e o sinal. srand(-2.9)
é o mesmo que srand(2)
.
Aqui está um exemplo de código que mostra:
#!/usr/bin/perl
use strict;
use warnings;
foreach my $n (-2, 2, 2.1, 2.9, -2.1, -2.9) {
my $real_n = srand($n);
my @arr;
foreach (1..5) {
push @arr, int(rand(10));
}
printf "%4s %s (%s)\n", $n, $real_n, join(', ', @arr);
}
A partir da versão Perl 5.14 função srand()
sempre retorna o número de 1
a 4294967296
, ou linha 0 but true
.
Este número é um número de seqüência, que é usada na função rand()
.
Se a função srand()
chamar sem argumentos, então ela irá retornar um número
a sequência, que foi instalado automaticamente.
Se a função chamar, com o argumento, então ela retornará o valor de número de seqüência, que foi instalada a partir desse argumento:
#!/usr/bin/perl
use feature qw(say);
say srand(1573); # 1573
say srand(-2.9); # 2
É interessante que para a seqüência com o número 0
a função retorna a string 0 but true
:
#!/usr/bin/perl
print srand(0);
A versão do Perl 5.14 função srand()
sempre retornará o número de 1
.
Aqui está a saída do comando perldoc -f srand
:
srand EXPR
srand Sets and returns the random number seed for the "rand" operator.
The point of the function is to "seed" the "rand" function so
that "rand" can produce a different sequence each time you run
your program. When called with a parameter, "srand" uses that
for the seed; otherwise it (semi-)randomly chooses a seed. In
either case, starting with Perl 5.14, it returns the seed. To
signal that your code will work *only* on Perls of a recent
vintage:
use 5.014; # so srand returns the seed
If "srand" is not called explicitly, it is called implicitly
without a parameter at the first use of the "rand" operator.
However, there are a few situations where programs are likely to
want to call "srand". One is for generating predictable results,
generally for testing or debugging. There, you use
"srand($seed)", with the same $seed each time. Another case is
that you may want to call "srand" after a "fork" to avoid child
processes sharing the same seed value as the parent (and
consequently each other).
Do not call "srand()" (i.e., without an argument) more than once
per process. The internal state of the random number generator
should contain more entropy than can be provided by any seed, so
calling "srand" again actually *loses* randomness.
Most implementations of "srand" take an integer and will
silently truncate decimal numbers. This means "srand(42)" will
usually produce the same results as "srand(42.1)". To be safe,
always pass "srand" an integer.
A typical use of the returned seed is for a test program which
has too many combinations to test comprehensively in the time
available to it each run. It can test a random subset each time,
and should there be a failure, log the seed used for that run so
that it can later be used to reproduce the same results.
"rand" is not cryptographically secure. You should not rely on
it in security-sensitive situations. As of this writing, a
number of third-party CPAN modules offer random number
generators intended by their authors to be cryptographically
secure, including: Data::Entropy, Crypt::Random,
Math::Random::Secure, and Math::TrulyRandom.