Skip to content

Instantly share code, notes, and snippets.

@robdelacruz
Last active January 15, 2023 18:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robdelacruz/25d1bc5a7ea72bd86088d2f28f2ba5f9 to your computer and use it in GitHub Desktop.
Save robdelacruz/25d1bc5a7ea72bd86088d2f28f2ba5f9 to your computer and use it in GitHub Desktop.
Perl port of https://gist.github.com/mikelehen/3596a30bd69384624c11 - Firebase style push guids
#!/usr/bin/perl
use v5.14;
use POSIX;
use Time::HiRes qw/time gettimeofday usleep/;
# Usage:
# my $newId = gen_pushid();
#
# Ported from:
# https://gist.github.com/mikelehen/3596a30bd69384624c11
# ms since epoch
sub epochMs {
my ($sec, $microSec) = gettimeofday;
return int($sec*1000 + $microSec/1000);
}
sub gen_pushid {
state $_pushchars = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
state $_lastPushTime;
state @_randIndexes;
my $now = epochMs();
if ($now != $_lastPushTime) {
# Generate new set of random indexes to pushchars.
for (my $i=0; $i < 12; $i++) {
$_randIndexes[$i] = int(rand(64));
}
} else {
# Same time, so just increment previous random index.
for (my $i=0; $i < 12; $i++) {
$_randIndexes[$i] += 1;
if ($_randIndexes[$i] < 64) {
last;
}
$_randIndexes[$i] = 0; # carry inc to next digit
}
}
$_lastPushTime = $now;
my @id;
# Copy pushchars to @id columns [19..8] (rightmost index to left)
for my $idx (@_randIndexes) {
unshift @id, substr($_pushchars, $idx, 1);
}
# Add time-based pushchars to @id columns [7..0] (rightmost index to left)
for (my $i=0; $i < 8; $i++) {
unshift @id, substr($_pushchars, $now % 64, 1);
$now = int($now / 64);
}
my $sid = join("", @id);
return $sid;
}
@sergeevabc
Copy link

Dear @robdelacruz, what's the correct way to run it on Windows?
So far all I see is a blank screen after $ perl.exe gen_pushid.pl

@robdelacruz
Copy link
Author

Copy and paste the code in your perl file and call gen_pushid() as a function:

my $newid = gen_pushid();
print $newid;

@sergeevabc
Copy link

@robdelacruz, it works now, thank you!

$ perl.exe gen_pushid.pl
-NLqhMAi-EqgHRkEf6ov

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment