Searched for tag UUID and found 2 results in 0.5 ms

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:
Leave A Reply

Perl: Generate UUIDv4

I needed simple and portable way to generate a version 4 UUID in Perl, so I hacked apart various pieces of UUID::Tiny and came up with this.

sub uuidv4 {
    my $uuid = '';

    # Four random bytes
    for (my $i = 0; $i < 4; $i++) {
        $uuid .= pack('I', int(rand(2 ** 32)));
    }

    # Replace the version of the UUID with 4 (0x40)
    substr($uuid, 6, 1, chr(ord(substr($uuid, 6, 1)) & 0x0f | 0x40 ));

    my @parts = map { substr $uuid, 0, $_, '' } ( 4, 2, 2, 2, 6 );
    my @hex   = map { unpack("H*", $_) } @parts;
    my $ret   = join('-', @hex);

    return $ret;
}
Tags:
Leave A Reply