'In Perl, how can I generate random strings consisting of eight hex digits?
Using Perl, without using any extra modules that don't come with ActivePerl, how can I create a string of 8 characters from 0-F. example 0F1672DA? The padding should be controllable and exactly 8 characters is preferable.
More examples of the kinds of strings I would like to generate:
28DA9782
55C7128A
Solution 1:[1]
General example, allowing any range of characters:
my @chars = ('0'..'9', 'A'..'F');
my $len = 8;
my $string;
while($len--){ $string .= $chars[rand @chars] };
print "$string\n";
Solution 2:[2]
sprintf("%08X", rand(0xFFFFFFFF))
some people mentioned the windows-limit of rand with the MAX-Value of rand(0x7FFF) or rand(32768) decimal, i would overcome this with binary shifting-operator '<<'
# overcomes the windows-rand()-only-works-with-max-15bit-(32767)-limitation:
# needed 8*4==32bit random-number:
# first get the 15 high-significant bits shift them 17bits to the left,
# then the next 15bits shifted 2 bits to the left,
# then the last 2 bits with no shifting:
printf( '%08X', (
(rand(0x8000)<<17) + (rand(0x8000)<<2) + rand(0b100) )
);
But i consider this only as academic, because it is really awkward code which is difficult to understand.
I would not use this in real-life code, only if speed mater the most.
But maybe its the fastest solution and it's demonstrating a schema to overcome the limitation of the rand()-function under windows...
Solution 3:[3]
Use sprintf to convert numbers to hex.
$foo .= sprintf("%x", rand 16) for 1..8;
Solution 4:[4]
From the "golf" comment by daxim:
perl -e'print[0..9,A..F]->[rand 16]for 1..8'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Oleg V. Volkov |
| Solution 2 | |
| Solution 3 | Sinan Ünür |
| Solution 4 |
