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

unixman83 picture unixman83 · Apr 26, 2012 · Viewed 21.9k times · Source

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

Answer

Sinan Ünür picture Sinan Ünür · Apr 26, 2012

In principle, you ought to be able to do

#!/usr/bin/env perl

use strict; use warnings;

for (1 .. 10) {
    printf "%08X\n", rand(0xffffffff);
}

However, you may find out that —at least on some systems with some perls (if not all)— the range of rand is restricted to 32,768 values.

You can also study the source code of String::Random to learn how to generate random strings satisfying other conditions.

However, my caution against using the built in rand on Windows system still stands. See Math::Random::MT for a 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 issue with Perl's rand on Windows was fixed in 5.20:

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

Perl now uses its own internal drand48() implementation on all platforms. This does not make perl's rand cryptographically secure. [perl #115928]