Searched for tag ULID and found 1 results in 0.6 ms

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
    $bytes .= pack 'C*', map { int(rand(256)) } 1 .. 10;

    # base32 encoding
    my $bits  = '00' . unpack('B*', $bytes);

    # Chars to use for base32
    my @chars = split(//, '0123456789ABCDEFGHJKMNPQRSTVWXYZ');

    my $result = '';
    for (my $i = 0; $i < 130; $i += 5) {
        my $index = oct('0b' . substr($bits, $i, 5));
        $result .= $chars[$index];
    }

    return $result;
}

See also: UUIDv7

Tags:
Leave A Reply