Getting a random key from hash:
Getting a random element from array:
Generating a random IP address:
Generating a random Session ID:
Generating a random string
my $hash = {
key1 => 'val1',
key2 => 'val2',
key3 => 'val3'
};
print "\n Random key from hash : " . randomKey($hash);
sub randomKey
{
my $hashRef = shift;
my @keyArray = keys %$hashRef;
my $randVal = $keyArray[rand @keyArray];
return $randVal;
}
Getting a random element from array:
my @array = qw(element1 element2 element3);
print "\n Random element from array : " .randomElement(\@array);
sub randomElement
{
my $keyArray = shift;
my $arrLen = scalar @$keyArray -1;
my $randNum = int(rand($arrLen));
return $keyArray->[$randNum];
}
Generating a random IP address:
print "\n Random IP address: " . getRandomIP();
sub getRandomIP
{
return join ".", map int rand 256, 1 .. 4;
}
Generating a random Session ID:
print "\n Random Session ID : " . getRandomSessionID();
sub getRandomSessionID
{
return sprintf("%0.8x",rand()*0xffffffff);
}
Generating a random string
print "\n Random string of 15 chars : " . getRandomString(15);
sub getRandomString
{
my $len = shift;
my @chars=('a'..'z','A'..'Z','0'..'9');
my $random_string;
foreach (1..$len) {
$random_string.=$chars[rand @chars];
}
return $random_string;
}
Generating a random number:
ReplyDeleteprint "\n Random Number : " . getRandomNumber(1000);
sub getRandomNumber
{
my $maxNum = shift;
return int(rand($maxNum));
}