Perl: ULID generation
ULID's are an interesting way to generate globally unique identifiers. Here is a quickie Perl implementation to generate ULIDs. This implementation does not include the intra-millisecond monotonic increment however. If that feature is important to you consider checking out a more full-featured implementation like ULID::Tiny.
for (1 .. 5) {
say(ulid());
}
sub ulid {
my $ts = $_[0] || time() * 1000;
my $bytes = substr(pack("Q>", $ts), 2, 6);
# Append 10 random bytes
for (0 .. 9) { $bytes .= chr(int(rand(256))); }
# base32 encoding
my $bits = unpack("B*", $bytes);
my $pad = (5 - (length($bits) % 5)) % 5;
$bits .= '0' x $pad;
# Chars to use for base32
my @CROCKFORD_CHARS = split //, '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
my $result = '';
for (my $i = 0; $i < length($bits); $i += 5) {
my $chunk = substr($bits, $i, 5);
my $index = 0;
for my $bit (split //, $chunk) {
$index = ($index << 1) | $bit;
}
$result .= $CROCKFORD_CHARS[$index];
}
return $result;
}
See also: UUIDv7
Tags:


