Reputation: 1471
I want to create a ping number between 0 and 9999 because it will be used for a user to interact with other users.
I thought about:
sub create
{
$ping_num = rand( 1000 + int(9000) );
}
The problem is that $ping_num
should be unique. In this case, there is a small probability that when the create method is called twice, the $ping_number
will be the same.
Any ideas on how to make a unique random ping number?
Upvotes: 0
Views: 123
Reputation: 13792
This module maybe helpful: Data::UUID
It can generate UUIDs (Universally Unique Identifiers), also known as GUIDs (Globally Unique Identifiers). A UUID is 128 bits long, and is guaranteed to be different from all other UUIDs/GUIDs generated until 3400 year.
Upvotes: 4
Reputation: 75498
Try this example.
#!/usr/bin/perl
use strict;
use warnings;
my @random_array = ();
my $random_counter = 0;
sub random_create
{
my $r;
# 0 - 9999; 10000 possible values
my $MAX = 10000;
# Reset if maximum is reached.
# You could instead return -1 to tell the caller that maximum number of
# random values were already generated and create another function like
# random_reset() with same methods below.
if ($random_counter == $MAX) {
@random_array = ();
$random_counter = 0;
}
# Generate the number.
until (!undef($random_array[$r = int(rand($MAX))])) { }
# Record the number.
$random_array[$r] = 1;
$random_counter++;
# Return.
return $r;
}
print random_create()."\n";
Upvotes: 0