Tip: Creating a String of Random Hex Digits
Every once in a while a string of random hex digits comes in handy*, perhaps when you need a random alphanumeric name for something. The unpack
operator seems like it should come in handy for this purpose, given that it can translate character values into hex strings, and so it does. Here's a snippet that creates a string of 32 random hex digits:
my $rand_hex = join "", map { unpack "H*", chr(rand(256)) } 1..16;
rand(256)
produces floating-point numbers 0.0 <= n < 256.0
. unpack "H2"
turns a character (a single-character string to be precise) into a 2-character MSB-first hex string - the chr
is needed to turn the numeric value from rand
into a string. The map { ... } 1..16
creates a list of 16 different 2-character strings, and join
gloms them all together.
Here's another - simpler - way to generate 32 random hex digits:
use Digest::MD5 qw(md5_hex);
my $rand_hex2 = md5_hex(rand);
*Or maybe you think that Perl looks like random hex digits all on its own. Most people, however, think it looks like modem line noise $$817 d3#@ ss NO CARRIER