In Perl, how can I generate random strings of eight hexadecimal digits?

Using Perl, without using any additional modules that are not included in ActivePerl, how can I create a string of 8 characters from 0-F. Example 0F1672DA ? The pad should be manageable and it is advisable to use only 8 characters.

Additional examples of line types that I would like to generate:

 28DA9782 55C7128A 
+6
source share
4 answers

Basically, you should be able to do

 #!/usr/bin/env perl use strict; use warnings; for (1 .. 10) { printf "%08X\n", rand(0xffffffff); } 

However, you can find out that, at least on some systems with some perl (if not all) - the range of rand limited to 32,768 values .

You can also examine the source code of String :: Random to learn how to create random strings that satisfy other conditions.

However, my caution against using native rand on a Windows system is still worth it. See Math :: Random :: MT for high-quality RNG.

 #!/usr/bin/env perl use strict; use warnings; my @set = ('0' ..'9', 'A' .. 'F'); my $str = join '' => map $set[rand @set], 1 .. 8; print "$str\n"; 

PS: The problem with Perl rand on Windows was fixed in 5.20 :

This meant that the quality of perl random numbers would vary from platform to platform, from 15 bits of rand () on Windows to 48 bits on POSIX platforms like Linux with drand48 ().

Perl now uses its own internal implementation of drand48 () on all platforms. This does not do cryptographic security perl rand. [perl # 115928]

+15
source

A common example that allows you to use any range of characters:

 my @chars = ('0'..'9', 'A'..'F'); my $len = 8; my $string; while($len--){ $string .= $chars[rand @chars] }; print "$string\n"; 
+7
source

Use sprintf to convert numbers to hex.

 $foo .= sprintf("%x", rand 16) for 1..8; 
+4
source
 sprintf("%08X", rand(0xFFFFFFFF)) 

some people mentioned the window limit of rand with the MAX value of rand (0x7FFF) or rand (32768) decimal, I would overcome this with the binary shift operator '<' lt

 # 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 academic, because it is really inconvenient code that is difficult to understand.
I would not use this in real code only if the speed is greater. But perhaps this is the fastest solution and demonstrates a scheme to overcome the limitations of the rand () function under windows ...

+4
source

Source: https://habr.com/ru/post/914242/


All Articles