Digest and identifiers

TL;DR

Digest comes handy for generating quick and dirty identifiers.

From time to time it happens that I have to generate some reasonably unique identifier. There are of course libraries to do this (UUID comes to mind), but sometimes they are overkill.

In addition to be unique, it’s good if this identifier is also restricted to a set of characters, e.g. it has no spaces or other non-alphanumeric stuff; this can ease e.g. parsing of some output at a later stage.

For this occasions, I think Digest offers a reasonable low-cost alternative, for example using directly one of the implementation (Digest::MD5 in this specific case):

$ perl -MDigest::MD5=md5_hex -le 'print md5_hex(time() . rand())'
fa1e572e21fcaeb899c67a0c687a4cb7
$ perl -MDigest::MD5=md5_hex -le 'print md5_hex(time() . rand())'
6401fdf48cdb4c7920148ff335d82550

Of course you can pre-pend a specific letter or the character _ if you want what a programming language would normally consider an identifier, as well as cut it to a specific length if it’s too many characters.

$ perl -MDigest::MD5=md5_hex \
    -le 'print substr "_" . md5_hex(time() . rand()), 0, 15'
_327b39ebed019f
$ perl -MDigest::MD5=md5_hex \
    -le 'print substr "_" . md5_hex(time() . rand()), 0, 15'
_b13534165e173d

Cheers!


Comments? Octodon, , GitHub, Reddit, or drop me a line!