blib/lib/ULID/example.pl untested

filter: Statementstmt 0.0% 0 / 54 Branchbran 0.0% 0 / 12 Conditioncond 0.0% 0 / 13 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 6 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 94 CC 7 SCAR 35.1
CC
7
Cov
0%
color
56.0
BEGIN
2.0
BEGIN
2.0
CRAP 33.5
1 #!/usr/bin/env perl
2 use strict;
3 use warnings;
4 use v5.16;
5 use ULID::Tiny qw(ulid ulid_date);
6 use Time::HiRes qw(time);
7  
8 my %opts = ();
9  
10 ################################################################################
11  
12 print "Monotonically increasing ULIDs:\n";
13  
14 # Generate a ULID and inspect it
15 for (1 .. 5) {
16 my $id = ulid();
17 say "Generated: $id";
18 }
19  
20 ################################################################################
21  
22 %opts = ( unique => 1);
23  
24 print "\n";
25 print "Unique ULIDs:\n";
26  
27 # Generate a ULID and inspect it
28 for (1 .. 5) {
29 my $id = ulid(%opts);
30 say "Generated: $id";
31 }
32  
33 ################################################################################
34  
35 %opts = ( unique => 0);
36  
37 print "\n";
38 print "Visual of timestamp vs random:\n";
39 # Generate a ULID and inspect it
40 for (1 .. 5) {
41 my $id = ulid(%opts);
42 my $p1 = color('194', substr($id, 0, 10));
43 my $p2 = color('230', substr($id, 10));
44 say "Generated: $p1$p2";
45 }
46  
47 ################################################################################
48 ################################################################################
49  
50 # String format: '115', '165_bold', '10_on_140', 'reset', 'on_173', 'red', 'white_on_blue'
51 sub color {
52 my ($str, $txt) = @_;
53  
54 if (-t STDOUT == 0 || $ENV{NO_COLOR}) { return $txt // ""; } # No interactive terminal
55 if (!length($str) || $str eq 'reset') { return "\e[0m"; } # No string = RESET
56  
57 # Some predefined colors/commands
58 my %color_map = qw(red 160 blue 27 green 34 yellow 226 orange 214 purple 93 white 15 black 0);
59 my %cmd_map = qw(bold 1 italic 3 underline 4 blink 5 inverse 7);
60  
61 # Pre-process the string.
62 $str =~ s/on_/-/; # "on_" becomes a negative number
63 $str =~ s|([A-Za-z]+)|$color_map{$1} // $1|eg; # command number
64  
65 my @parts = split("_", $str);
66 foreach my $p (@parts) {
67 my $cmd_num = $cmd_map{$p // 0};
68  
69 if ($cmd_num) { $p = $cmd_num; }
70 elsif (defined($p) && $p =~ /^-(.+)/) { $p = "48;5;$p"; }
71 elsif (defined($p)) { $p = "38;5;$p"; }
72 }
73  
74 my $ret = "\e[" . join(";", @parts) . "m";
75  
76 if (defined($txt)) { $ret .= $txt . "\e[0m"; }
77  
78 return $ret;
79 }