Perl: UUIDv7
Reddit had a mini challenge about implementing UUIDv7 in various languages. I whipped up a Perl implementation that turned out pretty well. I submitted it to the official GitHub repo and it was accepted.
sub uuidv7 {
# current timestamp in ms
my $timestamp = int(time() * 1000);
my $uuid = substr(pack("Q>", $timestamp), 2, 6);
# Append ten random bytes
for (1 .. 10) { $uuid .= chr(int(rand(256))); }
# version and variant
substr($uuid, 6, 1, chr((ord(substr($uuid, 6, 1)) & 0x0F) | 0x70));
substr($uuid, 8, 1, chr((ord(substr($uuid, 8, 1)) & 0x3F) | 0x80));
my @parts = map { substr $uuid, 0, $_, '' } ( 4, 2, 2, 2, 6 );
my @hex = map { unpack("H*", $_) } @parts;
my $ret = join('-', @hex);
return $ret;
}
See also: UUIDv4 in Perl.
Tags:


