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;
}
Leave A Reply
All content licensed under the Creative Commons License