blib/lib/Cn/Util.pm

filter: Statementstmt 95.0% 476 / 501 Branchbran 83.3% 230 / 276 Conditioncond 65.2% 77 / 118 MC/DCmcdc 47.7% 32 / 67 Subroutinesub 97.4% 38 / 39 Podpod 100% 10 / 10 totaltotal 85.3% 863 / 1011 CC 202 SCAR 27.3
CC
202
Cov
87%
_structure_describe
29.0
structure
26.5
dir
26.4
CRAP 15.3
↑ Summary
1 # ABSTRACT: Small everyday helpers: directory listing, shell commands, JSON files, number formatting, and data-structure shapes
2 11 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 11 ▶use feature 'say';
Subroutine BEGIN: called CC=1 SCAR=0.0
4 11 ▶use warnings FATAL => 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 # Devel::Confess is loaded for its side effect, which is process-wide: it
6 # installs $SIG{__DIE__} and $SIG{__WARN__} so that every die and warn in the
7 # program carries a stack trace. `use Cn::Util` has always given the caller
8 # this, so it stays at the top, where loading the module is enough.
9 11 ▶use Devel::Confess;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 package Cn::Util;
12 11 require 5.010001;
13 11 our $VERSION = 0.0243;
14 11 require Exporter;
15 11 our @ISA = ('Exporter');
16 11 our @EXPORT = qw(dir execute file2string format_commas json_file_to_ref random_key random_value ref_to_json_file st structure);
17  
18 # Startup cost. Everything other than the pragmas, Exporter and
19 # Devel::Confess is loaded on first use, not at `use Cn::Util`. Loading DDP,
20 # autodie, Capture::Tiny and JSON::MaybeXS eagerly cost ~40 ms of interpreter
21 # startup on every script that touched this module, even ones that only called
22 # format_commas().
23 #
24 # The rules that decide what can be deferred:
25 # - PRAGMAS (warnings, feature, autodie) act on the *compiler* for the
26 # enclosing lexical scope, so they can never be deferred. autodie was the
27 # single most expensive line here (~15 ms); this file does not use it, and
28 # the bare open()s it was covering carry explicit `or die`.
29 # - Exporter must exist at compile time (it supplies import()), but it is
30 # free -- it is already in memory as part of the core.
31 # - Everything else is a plain module, so `require` inside the sub that
32 # needs it works. `require` is idempotent and a repeat call is one %INC
33 # hash lookup, so putting it in the hot sub costs nothing measurable.
34 # - A runtime `require` does NOT run import(), so the imported short names
35 # (find, capture, decode_json, colored, blessed) are not available. Each
36 # call site below is therefore fully qualified. Calling a not-yet-loaded
37 # sub with a block prototype is also unparseable at compile time, which is
38 # why Capture::Tiny::capture is handed an explicit sub{} instead of a bare
39 # {}.
40  
41 # ---------------------------------------------------------------------------
42 # `use Cn::Util` hands the calling package three things besides @EXPORT:
43 # autodie, and DDP's p() and np().
44 #
45 # autodie is LEXICAL, and that is the hard case. It is Fatal underneath, and
46 # Fatal::import does a bare `caller()` with no $Level support: calling
47 # autodie->import() directly from in here makes Fatal believe the importing
48 # file is Cn/Util.pm. Its runtime leak-guard then sees calls arriving from a
49 # different file and correctly declines to apply -- open() in the caller just
50 # returns undef again, silently. Verified: the naive version does nothing at
51 # all.
52 #
53 # So the import has to be performed in a context where caller() reports the
54 # caller's package and file. A string eval carrying a #line directive does
55 # exactly that, and is the same trick Import::Into uses (not depended on here
56 # because it is not a core module). $line/$file come from our own caller, so
57 # autodie's scope starts at the `use Cn::Util` line, which is where a
58 # hand-written `use autodie` would have started it too.
59 #
60 # The eval only compiles a closure, and the import runs when that closure is
61 # called after the eval has returned, which is also what Import::Into does.
62 # Perls up to at least 5.12 keep a string eval's own %^H in force while the
63 # eval runs, and autodie 2.06 (core in 5.10.1 and 5.12.5) keeps the guard that
64 # un-installs it at the end of the scope in %^H: imported inside the eval,
65 # autodie was un-installed again as the eval returned, and a missing file
66 # opened in the caller returned false. t/00-load.t checks this.
67 #
68 # p() and np() are installed by _install_ddp_stubs(), below.
69 #
70 # NB: `use Cn::Util ();` skips import() entirely, per normal Perl semantics,
71 # so that is the escape hatch for a caller that wants none of this.
72 # ---------------------------------------------------------------------------
73 11 ▶sub import {
Subroutine import: called CC=2 SCAR=7.0
74 11 my $class = shift;
75 11 $class->export_to_level(1, $class, @_); # the @EXPORT subs, one level up
76  
77 11 my ($pkg, $file, $line) = caller;
78 11 _install_ddp_stubs($pkg);
79 11 require autodie;
80 11 ▶ my $autodie = eval qq{package $pkg;\n#line $line "$file"\nsub { autodie->import(':default') }}
Branch: 1 branch
BranchTrueFalseTotal
my $autodie = eval qq[package $pkg;\n#line $line "$file"\nsub { autodie->import(':default') }] or die "Cn::Util: could not propagate autodie to ${file}: $@" 11 0 11
81 or die "Cn::Util: could not propagate autodie to $file: $@";
82 11 $autodie->();
83 11 return;
84 }
85  
86 # Scripts rely on `use Cn::Util` giving them DDP's p() and np() without a
87 # `use DDP` of their own. These stubs keep that convenience without paying
88 # DDP's ~16 ms unless something actually prints. They are installed at the
89 # caller's `use` line, which is compile time for the rest of the caller, and
90 # with DDP's own prototype, because that is what makes `p @files` pass \@files
91 # rather than a flat list. On first call, DDP->import() is run as if from the
92 # caller's package, so it overwrites the stub there with the real thing.
93 #
94 # A p() or np() the caller already has -- its own, or DDP's from an earlier
95 # `use DDP` -- is left alone. Util.pm, which this module was before it was
96 # Cn::Util, compiled the stubs into main:: whenever it loaded, which redefined
97 # DDP's p() under its FATAL warnings when a script said `use DDP` first.
98 11 my %DDP_LOADED; # package => true once DDP's real p() and np() are installed there
99 my %DDP_STUB; # package => { name => the stub installed for it }, p and np
100  
101 11 ▶sub _install_ddp_stubs {
Subroutine _install_ddp_stubs: called CC=3 SCAR=11.0
102 11 my ($pkg) = @_;
103 11 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
104 11 for my $name ('p', 'np') {
105 22 my $glob = "${pkg}::$name";
106 22 ▶ next if defined &{$glob};
Branch: 1 branch
BranchTrueFalseTotal
if defined &{$glob;} 1 21 22
107 21 ▶ *{$glob} = $DDP_STUB{$pkg}{$name} = sub (\[@$%&];%) {
Subroutine __ANON__: called CC=2 SCAR=7.0
108 4 _load_ddp($pkg);
109 # A `p` that DDP did not replace -- an `alias` in ~/.dataprinter
110 # exports it under another name -- would otherwise be this stub
111 # again, and the goto would call it forever.
112 die "Cn::Util: DDP did not install ${pkg}::$name\n"
113 2 ▶ if \&{$glob} == $DDP_STUB{$pkg}{$name};
Branch: 1 branch
BranchTrueFalseTotal
if \&{$glob;} == $DDP_STUB{$pkg}{$name} 0 2 2
114 2 goto &{$glob};
115 21 };
116 }
117 11 return;
118 }
119  
120 4 ▶sub _load_ddp {
Subroutine _load_ddp: called CC=8 SCAR=21.2
121 4 my ($pkg) = @_;
122 # Marked loaded only once the import has succeeded. Marking it first made
123 # a second call after a failed load return here at once, and the stub's
124 # goto then called the stub itself, forever.
125 4 ▶ return if $DDP_LOADED{$pkg};
Branch: 1 branch
BranchTrueFalseTotal
if $DDP_LOADED{$pkg} 0 4 4
126 4 require DDP;
127 11 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
128 # DDP->import() exports both p() and np(), but a stub was installed only
129 # for a name the caller had no sub under, so the other -- or one the caller
130 # defined over a stub after its `use` line -- is the caller's own. Its
131 # glob is localised for the import, so DDP writes into a temporary that is
132 # discarded, and the caller's sub comes back untouched.
133 my %own = map {
134 2 my $glob = "${pkg}::$_";
135 4 ▶ $_ => (defined &{$glob} && \&{$glob} != ($DDP_STUB{$pkg}{$_} // 0));
Condition80%4/5
defined &{$glob;} && \&{$glob;} != ($DDP_STUB{$pkg}{$_} // 0)
!ll&&!rl&&r
031
$DDP_STUB{$pkg}{$_} // 0
l!l
31
MC/DC50%1/2
defined &{$glob;} && \&{$glob;} != ($DDP_STUB{$pkg}{$_} // 0)
defined &{$glob;} \&{$glob;} != ($DDP_STUB{$pkg}{$_} // 0)
MC/DC100%1/1
$DDP_STUB{$pkg}{$_} // 0
$DDP_STUB{$pkg}{$_}
Truth table66%2/3
A && B
A= defined &{$glob;}B= \&{$glob;} != ($DDP_STUB{$pkg}{$_} // 0)
ABresult
0X0
100
111
Truth table100%2/2
A
A= $DDP_STUB{$pkg}{$_}
Aresult
11
00
136 } 'p', 'np';
137 2 ▶ local *{"${pkg}::p"} if $own{p};
Branch: 1 branch
BranchTrueFalseTotal
if $own{"p"} 1 1 2
138 0 ▶ local *{"${pkg}::np"} if $own{np};
Branch: 1 branch
BranchTrueFalseTotal
if $own{"np"} 0 2 2
139 3 ▶ local $SIG{__WARN__} = sub {
Subroutine __ANON__: called CC=2 SCAR=7.6
140 3 ▶ warn @_ unless $_[0] =~ m{\ASubroutine \Q$pkg\E::n?p redefined};
Branch: 1 branch
BranchTrueFalseTotal
unless $_[0] =~ /\ASubroutine \Q$pkg\E::n?p redefined/ 0 3 3
141 2 };
142 # show_memsize needs Devel::Size, which is not a prerequisite; asked for
143 # without it, DDP warned "Devel::Size not found" on every first p() or np().
144 2 ▶ my $memsize = eval { require Devel::Size; 1 } ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require Devel::Size; 1 } } ? : 2 0 2
145 2 my $ok = eval qq{package $pkg;\nDDP->import({output => 'STDOUT', array_max => 10, show_memsize => $memsize, show_dualvar => 'off'}); 1};
146 2 ▶ die "Cn::Util: could not load DDP into $pkg: $@" unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 2 2
147 2 $DDP_LOADED{$pkg} = 1;
148 2 return;
149 }
150  
151 39 ▶sub dir {
Subroutine dir: called CC=26 SCAR=32.7
Pod documented
152 39 my %args = (
153 tests => 'f',
154 dir => '.',
155 regex => '.',
156 recursive => 0,
157 on_match => undef, # optional callback: streams results, keeps RAM flat
158 cpu => 1, # worker processes for a recursive walk; 1 = no forking
159 @_,
160 );
161  
162 39 my %allowed = map { $_ => 1 } qw(tests dir regex recursive on_match cpu);
163 39 ▶ if (my @bad = grep { !$allowed{$_} } keys %args) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@bad) = grep({not $allowed{$_};} keys %args)) 1 38 39
164 1 die "Unrecognized arguments: @bad\nAccepted args: "
165 . join(', ', sort keys %allowed);
166 }
167 # Added 's' (non-zero size), removed 't' (tty test - meaningless on a path)
168 # Checked here so that an undef gets this message rather than "Use of
169 # uninitialized value" from the first line that reads it. recursive is
170 # left out: undef is as false there as 0.
171 38 for my $name (qw(tests dir regex cpu)) {
172 149 ▶ die "$name must be defined" unless defined $args{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{$name} 1 148 149
173 }
174 die "on_match must be a code reference"
175 37 ▶ if defined $args{on_match} && ref $args{on_match} ne 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"on_match"} and ref $args{"on_match"} ne "CODE" 1 36 37
Condition100%3/3
defined $args{"on_match"} and ref $args{"on_match"} ne "CODE"
!ll&&!rl&&r
3421
MC/DC100%2/2
defined $args{"on_match"} and ref $args{"on_match"} ne "CODE"
defined $args{"on_match"} ref $args{"on_match"} ne "CODE"
Truth table100%3/3
A and B
A= defined $args{"on_match"}B= ref $args{"on_match"} ne "CODE"
ABresult
0X0
100
111
176 die "Unrecognized characters in tests: $args{tests}"
177 36 ▶ if $args{tests} =~ /[^rwxoRWXOezsfdlpSbcugkTB]/;
Branch: 1 branch
BranchTrueFalseTotal
if $args{"tests"} =~ /[^rwxoRWXOezsfdlpSbcugkTB]/ 1 35 36
178 die "cpu must be a positive integer, got '$args{cpu}'"
179 35 ▶ unless $args{cpu} =~ /\A[1-9][0-9]*\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"cpu"} =~ /\A[1-9][0-9]*\z/ 2 33 35
180 33 ▶ my $re = eval { qr/$args{regex}/ }
Branch: 1 branch
BranchTrueFalseTotal
my $re = eval { do { qr/$args{"regex"}/ } } or die qq[Invalid regex '$args{"regex"}': $@] 32 1 33
181 or die "Invalid regex '$args{regex}': $@";
182 # Compile the tests once. The first test stats the path; every later test
183 # reuses the stat buffer via the special '_' filehandle, so N tests cost
184 # one stat(2) syscall instead of N (~2.4x faster for 4 tests).
185 # -l needs lstat, so it is hoisted to the front, and the test after it
186 # must re-stat the real path (otherwise '_' holds lstat data, or -l _
187 # would be a fatal error).
188 32 my @t = split //, $args{tests};
189 32 @t = ((grep { $_ eq 'l' } @t), (grep { $_ ne 'l' } @t));
190 32 my @parts;
191 32 my $fresh = 1; # 1 = the next test must stat the path itself rather than reuse '_'
192 32 for my $t (@t) {
193 0 ▶ if ($t eq 'l') { push @parts, '-l $_[0]'; $fresh = 1 }
Branch: 2 branches
BranchTrueFalseTotal
if ($t eq 'l') { } 0 28 28
elsif ($fresh) { } 28 0 28
194 28 elsif ($fresh) { push @parts, "-$t \$_[0]"; $fresh = 0 }
195 0 else { push @parts, "-$t _" }
196 }
197 my $tester = @parts
198 ? (eval 'sub { ' . join(' && ', @parts) . ' }'
199 or die "Failed to compile tests: $@")
200 32 ▶ : sub { 1 }; # empty tests string now means "no filtering", not "nothing matches"
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
@parts ? : 28 4 32
Condition50%1/2
eval 'sub { ' . join(" && ", @parts) . ' }' or die "Failed to compile tests: $@"
l!l
280
MC/DC0%0/1
eval 'sub { ' . join(" && ", @parts) . ' }' or die "Failed to compile tests: $@"
eval 'sub { ' . join(" && ", @parts) . ' }'
Truth table50%1/2
A
A= eval 'sub { ' . join(" && ", @parts) . ' }'
Aresult
11
00
201  
202 32 my $target_dir = $args{dir};
203 # On Windows every "\" in dir becomes "/", so that every path dir() returns
204 # there uses "/" alone. This began as matching File::Find, which did the
205 # same to its starting path (the "canonicalize directory separators" step
206 # of _find_opt in 1.44, on the Strawberry Perl 5.42 smoker) while the
207 # recursive walk used it, and mixed separators made that walk report its
208 # own root. Only on MSWin32: elsewhere "\" is an ordinary character in a
209 # file name.
210 32 my $is_win32 = $^O eq 'MSWin32';
211 32 ▶ $target_dir =~ tr{\\}{/} if $is_win32;
Branch: 1 branch
BranchTrueFalseTotal
if $is_win32 0 32 32
212 # Strip trailing slashes, but keep a root intact: "/", and on Windows "C:/",
213 # because "C:" alone is the current directory on drive C, not its root.
214 # Collapsing first is what turns "///" into "/"; it used to be left as it
215 # was, to be joined as "////etc".
216 32 $target_dir =~ s{/+\z}{/}s;
217 32 ▶ $target_dir =~ s{/\z}{}s
Branch: 2 branches
BranchTrueFalseTotal
unless $target_dir =~ ($is_win32 ? qr"\A(?:[A-Za-z]:)?/\z"s : qr"\A/\z"s) 30 2 32
$is_win32 ? : 0 32 32
218 unless $target_dir =~ ($is_win32 ? qr{\A(?:[A-Za-z]:)?/\z}s : qr{\A/\z}s);
219 # "." is left off the front of results; a root, the only $d that still
220 # ends in "/", must not become "//etc" or "C://etc".
221 720 ▶ my $join = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
222 720 my ($d, $item) = @_;
223 720 ▶ $d eq '.' ? $item : $d =~ m{/\z} ? "$d$item" : "$d/$item"
Branch: 2 branches
BranchTrueFalseTotal
$d eq '.' ? : 26 694 720
$d =~ m[/\z] ? : 42 652 694
224 32 };
225  
226 32 my $cb = $args{on_match};
227 32 my @items;
228 32 ▶ my $emit = $cb // sub { push @items, $_[0] };
Subroutine __ANON__: called CC=1 SCAR=0.1
Condition66%2/3
$cb // sub { push @items, $_[0]; }
l!l&&r!l&&!r
2300
MC/DC0%0/2
$cb // sub { push @items, $_[0]; }
$cb sub { push @items, $_[0]; }
Truth table66%2/3
A // B
A= $cbB= sub { push @items, $_[0]; }
ABresult
1X1
011
000
229  
230 32 ▶ if ($args{recursive}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'recursive'}) { } 23 9 32
231 # Walk everything strictly below $start, depth first, handing each
232 # match to $sink. _dir_level returns a directory's subdirectories
233 # without the symlinks among them, so the walk does not follow links;
234 # but opendir follows $start itself, so a dir that is a symlink to a
235 # directory is listed through the link.
236 #
237 # File::Find did this walk up to 0.024. Over ~/perl5 (279,000
238 # entries, warm cache, 2026-11-09) it took 1.06 s of user CPU to this
239 # loop's 0.43 s, for the same system time: the two make the same stat
240 # and lstat calls. It also lstat()ed its starting path, so a symlinked
241 # dir needed listing by hand before it, and on Windows it rewrote the
242 # separators of that path, which the "\" conversion above is for.
243 11 ▶ my $find = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
244 11 my ($start, $sink) = @_;
245 11 my @todo = ($start);
246 11 ▶ push @todo, _dir_level(pop @todo, $re, $tester, $join, $sink) while @todo;
Branch: 1 branch
BranchTrueFalseTotal
@todo and do { push @todo, _dir_level(pop @todo, $re, $tester, $join, $sink) } 206 9 215
247 9 return;
248 23 };
249 23 ▶ if ($args{cpu} == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'cpu'} == 1) { } 11 12 23
250 11 $find->($target_dir, $emit);
251 } else {
252 12 _dir_parallel($target_dir, $args{cpu}, $re, $tester, $join, $find, $emit);
253 }
254 } else {
255 # cpu is ignored here on purpose: one readdir plus one stat per entry
256 # is ~6 us warm, far below the cost of forking and shipping results back.
257 9 ▶ opendir my $dh, $target_dir
Branch: 1 branch
BranchTrueFalseTotal
opendir my $dh, $target_dir or die "Cannot open directory ${target_dir}: $!" 8 1 9
258 or die "Cannot open directory $target_dir: $!";
259 8 ▶ while (defined(my $item = readdir $dh)) { # defined(): a file named "0" is falsy
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $item = readdir $dh)) 96 8 104
260 96 ▶ next if $item =~ /\A\.\.?\z/; # \A..\z: "$" would match before a trailing \n
Branch: 1 branch
BranchTrueFalseTotal
if $item =~ /\A\.\.?\z/ 16 80 96
261 80 ▶ next if $item !~ $re;
Branch: 1 branch
BranchTrueFalseTotal
unless $item =~ /$re/ 11 69 80
262 69 my $path = $join->($target_dir, $item);
263 69 ▶ $emit->($path) if $tester->($path);
Branch: 1 branch
BranchTrueFalseTotal
if &$tester($path) 62 7 69
264 }
265 8 closedir $dh;
266 }
267 27 ▶ return $cb ? () : @items;
Branch: 1 branch
BranchTrueFalseTotal
$cb ? : 2 25 27
268 }
269  
270 # Jobs handed out per worker. Parallel::ForkManager starts a new job whenever
271 # a worker finishes, so more jobs than workers is what evens out a tree whose
272 # subdirectories differ wildly in size; each job costs one fork plus one
273 # Storable round-trip through a temp file, so too many jobs loses again.
274 # Measured 2026-09-23, 20-core NVMe box, warm cache, best of 3, seconds:
275 #
276 # tree (files) serial k=1 k=2 k=4 k=8 k=16
277 # ~/perl5 (150k), cpu=8 1.23 0.95 0.25 0.29 0.36 0.47
278 # ~/perl5 (150k), cpu=4 1.23 1.03 0.82 0.39 0.45 0.61
279 # perlbrew/build (120k), cpu=8 0.75 0.19 0.24 0.25 0.33 0.44
280 #
281 # k=1 and k=2 collapse on the skewed tree; 4 is the smallest value that does
282 # not. Re-run: edit the value below, then time
283 # perl -Ilib -MCn::Util -e 'dir(dir => $ARGV[0], recursive => 1, cpu => 8)' TREE
284 11 my $DIR_JOBS_PER_CPU = 4;
285  
286 # Hand each entry of directory $d that matches $re and $tester to $emit, and
287 # return its subdirectories, leaving out symlinks to directories so that a
288 # recursive walk does not follow them. One level of a recursive dir(): the
289 # serial walk is a loop over it, and so are the parallel walk's breadth-first
290 # levels and each of its workers.
291 218 ▶sub _dir_level {
Subroutine _dir_level: called CC=8 SCAR=20.8
292 218 my ($d, $re, $tester, $join, $emit) = @_;
293 218 ▶ opendir my $dh, $d or die "Cannot open directory $d: $!";
Branch: 1 branch
BranchTrueFalseTotal
opendir my $dh, $d or die "Cannot open directory ${d}: $!" 215 3 218
294 215 my @sub;
295 215 ▶ while (defined(my $item = readdir $dh)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $item = readdir $dh)) 1081 215 1296
296 1081 ▶ next if $item =~ /\A\.\.?\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $item =~ /\A\.\.?\z/ 430 651 1081
297 651 my $path = $join->($d, $item);
298 651 ▶ $emit->($path) if $item =~ $re && $tester->($path);
Branch: 1 branch
BranchTrueFalseTotal
if $item =~ /$re/ and &$tester($path) 334 317 651
Condition100%3/3
$item =~ /$re/ and &$tester($path)
!ll&&!rl&&r
67250334
MC/DC100%2/2
$item =~ /$re/ and &$tester($path)
$item =~ /$re/ &$tester($path)
Truth table100%3/3
A and B
A= $item =~ /$re/B= &$tester($path)
ABresult
0X0
100
111
299 651 ▶ push @sub, $path if !-l $path && -d _; # -l: lstat, so -d _ is the entry itself, not its target
Branch: 1 branch
BranchTrueFalseTotal
if not -l $path and -d _ 340 311 651
Condition100%3/3
not -l $path and -d _
!ll&&!rl&&r
18293340
MC/DC100%2/2
not -l $path and -d _
not -l $path -d _
Truth table100%3/3
not(A) and B
A= not -l $pathB= -d _
ABresult
0X0
100
111
300 }
301 215 closedir $dh;
302 215 return @sub;
303 }
304  
305 # Recursive dir() across $cpu worker processes. Results come back to this
306 # process and go through $emit here, so an on_match closure still sees and
307 # mutates the caller's variables -- it just runs after a whole job's batch
308 # arrives rather than per file, and match order differs from the serial walk.
309 12 ▶sub _dir_parallel {
Subroutine _dir_parallel: called CC=12 SCAR=29.7
310 12 my ($root, $cpu, $re, $tester, $join, $find, $emit) = @_;
311 12 require Parallel::ForkManager; # not core, and only cpu > 1 needs it
312  
313 # One subtree per job would starve the pool whenever a single directory
314 # holds most of the tree (~/perl5: one of 3 top-level dirs has 99% of the
315 # files, and a top-level split gave no speedup at any cpu). So walk
316 # breadth-first here until a level is wide enough to share out, testing
317 # the entries of every level walked; the final level's directories are
318 # already tested and become the jobs.
319 12 my $want = $cpu * $DIR_JOBS_PER_CPU;
320 12 my @level = ($root);
321 12 ▶ while (@level && @level < $want) {
Branch: 1 branch
BranchTrueFalseTotal
if (@level and @level < $want) 12 11 23
Condition66%2/3
@level and @level < $want
!ll&&!rl&&r
01112
MC/DC50%1/2
@level and @level < $want
@level @level < $want
Truth table66%2/3
A and B
A= @levelB= @level < $want
ABresult
0X0
100
111
322 12 @level = map { _dir_level($_, $re, $tester, $join, $emit) } @level;
323 }
324 11 ▶ return unless @level;
Branch: 1 branch
BranchTrueFalseTotal
unless @level 0 11 11
325  
326 11 my @jobs;
327 11 push @{ $jobs[$_ % $want] }, $level[$_] for 0 .. $#level;
328  
329 # A worker hands its results back in a Storable file of its own, named by
330 # its pid, and leaves with POSIX::_exit, rather than through
331 # Parallel::ForkManager's finish(), whose CORE::exit ran the caller's END
332 # blocks and destructors in every worker: an END that removed a lock file
333 # or printed a summary did it a dozen times, and a database handle was
334 # closed from under the parent. On Windows a worker is a thread of this
335 # process, and _exit would end the whole of it, so there it still calls
336 # finish(). newdir() removes the directory only in this process, by pid.
337 11 require POSIX;
338 11 require Storable;
339 11 require File::Temp;
340 11 my $is_win32 = $^O eq 'MSWin32';
341 11 my $tmp = File::Temp->newdir;
342  
343 11 my @errors;
344 11 my $pm = Parallel::ForkManager->new($cpu);
345 # The default 1 s poll in wait_all_children added a flat 1.01 s to every
346 # call, measured; 0 makes it block in waitpid instead.
347 11 $pm->set_waitpid_blocking_sleep(0);
348 92 ▶ $pm->run_on_finish(sub {
Subroutine __ANON__: called CC=8 SCAR=24.0
349 92 my ($pid, $exit, undef, $signal) = @_;
350 92 my $file = "$tmp/$pid";
351 92 ▶ my $data = -e $file ? eval { Storable::retrieve($file) } : undef;
Branch: 1 branch
BranchTrueFalseTotal
-e $file ? : 92 0 92
352 92 ▶ unlink $file if -e $file;
Branch: 1 branch
BranchTrueFalseTotal
if -e $file 92 0 92
353 92 ▶ if ($signal || $exit || !$data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($signal or $exit or not $data) 0 92 92
Condition33%2/6
$signal or $exit or not $data
l!l&&r!l&&!r
0092
$signal or $exit
l!l&&r!l&&!r
0092
MC/DC0%0/3
$signal or $exit or not $data
$signal $exit not $data
Truth table25%1/4
A or B or not(C)
A= $signalB= $exitC= not $data
ABCresult
1XX1
01X1
0011
0000
354 0 push @errors, "dir: worker $pid died (exit $exit, signal $signal)";
355 0 return;
356 }
357 92 ▶ push @errors, $data->{error} if defined $data->{error};
Branch: 1 branch
BranchTrueFalseTotal
if defined $data->{"error"} 1 91 92
358 92 $emit->($_) for @{ $data->{paths} };
359 11 });
360 11 for my $job (@jobs) {
361 92 ▶ $pm->start and next;
Branch: 1 branch
BranchTrueFalseTotal
$pm->start and next 92 0 92
362 0 my @found;
363 0 ▶ my $ok = eval { $find->($_, sub { push @found, $_[0] }) for @$job; 1 };
Subroutine __ANON__: not called CC=1 SCAR=6.9
364 0 ▶ my $error = $ok ? undef : "$@"; # taken now: the eval below clears $@ as it starts
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 0 0 0
365 0 my $stored = eval { Storable::store({ paths => \@found, error => $error }, "$tmp/$$") };
366 0 ▶ my $code = $stored ? 0 : 1; # 1 = the results could not be written
Branch: 1 branch
BranchTrueFalseTotal
$stored ? : 0 0 0
367 0 ▶ $pm->finish($code) if $is_win32;
Branch: 1 branch
BranchTrueFalseTotal
if $is_win32 0 0 0
368 0 POSIX::_exit($code);
369 }
370 11 $pm->wait_all_children;
371 11 ▶ die join "\n", @errors if @errors;
Branch: 1 branch
BranchTrueFalseTotal
if @errors 1 10 11
372 10 return;
373 }
374  
375 15 ▶sub execute {
Subroutine execute: called CC=16 SCAR=27.8
Pod documented
376 15 my ($cmd, $return, $die) = @_;
377 15 ▶ $return = 'exit' unless defined $return;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $return 4 11 15
378 15 ▶ $die = 1 unless defined $die;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $die 12 3 15
379 # \A..\z: "$" also matches before a trailing newline, so "exit\n" passed
380 # here, ran the command, and only then died with "broke pigeonholes".
381 15 ▶ if ($return !~ m/\A(?:exit|stdout|stderr|all)\z/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($return =~ /\A(?:exit|stdout|stderr|all)\z/) 2 13 15
382 2 die "you gave \$return = \"$return\", while this subroutine only accepts exit, stdout, stderr or all";
383 }
384 13 require Capture::Tiny; # ~7.5 ms
385 # Capture::Tiny redirects fd 1 and fd 2 and nothing else, so the child still
386 # inherits the parent's fd 0. A child that prompts -- rm on a
387 # write-protected file, cp -i, apt -- prompts only when fd 0 is a tty, then
388 # writes its question into the captured stderr where nobody can see it and
389 # blocks on the terminal for an answer the user does not know is wanted.
390 # (Observed 2026-09-13: `rm -r` on read-only cl.tex hung jobsearch/tex/tar.pl
391 # indefinitely.) Pointing fd 0 at /dev/null turns the prompt into an instant
392 # EOF, so such a child declines and exits instead of hanging.
393 #
394 # What goes on fd 0 is the read end of an empty pipe whose write end is
395 # closed, and only the descriptor is swapped, with dup2; the STDIN handle is
396 # left alone. Before system() forks, perl flushes every handle, and flushing
397 # one it reads from lseek()s its descriptor back to the position perl has
398 # read up to and, if that seek succeeds, discards the read-ahead buffer. A
399 # pipe cannot seek, so the buffer survives; the null device can, so with it
400 # on fd 0, as in 0.023, the buffered input was lost:
401 # `printf 'a\nb\nc\n' | perl -e 'while (<STDIN>) { print; execute("true") }'`
402 # printed only "a". Whatever holds fd 0 -- STDIN, or another handle when
403 # STDIN is closed -- is saved and put back, and fd 0 is closed again if it
404 # was closed before.
405 #
406 # fd 0 is saved before the pipe is made: when it is free, pipe() takes it,
407 # and a dup of fd 0 made afterwards saved the pipe, which was then
408 # "restored", leaving fd 0 open on it.
409 13 require POSIX;
410 13 my $saved_fd0 = POSIX::dup(0); # undef = fd 0 was closed
411 13 ▶ pipe my $eof, my $writer or die "cannot make a pipe for the command's input: $!";
Branch: 1 branch
BranchTrueFalseTotal
pipe my $eof, my $writer or die "cannot make a pipe for the command's input: $!" 13 0 13
412 13 close $writer;
413 13 my $eof_on_fd0 = fileno $eof == 0; # 1 = fd 0 was free and pipe() took it
414 13 ▶ unless ($eof_on_fd0) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($eof_on_fd0) 12 1 13
415 12 ▶ defined POSIX::dup2(fileno $eof, 0) or die "cannot point fd 0 at an empty pipe: $!";
Branch: 1 branch
BranchTrueFalseTotal
defined POSIX::dup2(fileno $eof, 0) or die "cannot point fd 0 at an empty pipe: $!" 12 0 12
416 12 close $eof;
417 }
418 # An explicit sub{} rather than capture { ... }: the prototype that makes
419 # the block form legal is not visible at compile time under a runtime
420 # require, so perl would try to parse the block as an anonymous hash.
421 # The eval is so that fd 0 is restored even when capture() dies; 0.023 left
422 # it on the null device for the rest of the program.
423 13 my ($stdout, $stderr, $exit);
424 13 my $ok = eval {
425 12 ▶ ($stdout, $stderr, $exit) = Capture::Tiny::capture(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
426 12 system( $cmd )
427 13 });
428 12 1;
429 };
430 13 my $err = $@;
431 13 ▶ if (defined $saved_fd0) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $saved_fd0) { } 12 1 13
elsif ($eof_on_fd0) { } 1 0 1
432 12 ▶ defined POSIX::dup2($saved_fd0, 0) or die "cannot restore fd 0: $!";
Branch: 1 branch
BranchTrueFalseTotal
defined POSIX::dup2($saved_fd0, 0) or die "cannot restore fd 0: $!" 12 0 12
433 12 POSIX::close($saved_fd0);
434 } elsif ($eof_on_fd0) {
435 1 close $eof;
436 } else {
437 0 POSIX::close(0);
438 }
439 13 ▶ die $err unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 1 12 13
440 # Truthiness, as the documentation describes it. `$die == 1` made 'yes' die
441 # with "isn't numeric" and made 2 mean "do not die".
442 12 ▶ if ($die && $exit != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($die and $exit != 0) 3 9 12
Condition100%3/3
$die and $exit != 0
!ll&&!rl&&r
183
MC/DC100%2/2
$die and $exit != 0
$die $exit != 0
Truth table100%3/3
A and B
A= $dieB= $exit != 0
ABresult
0X0
100
111
443 3 say STDERR "exit = $exit";
444 3 say STDERR "STDOUT = $stdout";
445 3 say STDERR "STDERR = $stderr";
446 3 die "$cmd\n failed";
447 }
448 9 ▶ return $exit if $return eq 'exit';
Branch: 1 branch
BranchTrueFalseTotal
if $return eq "exit" 3 6 9
449 # chomp removes whatever $/ is, and $/ is the caller's: under a caller's
450 # `local $/;` it removed nothing, and "hi\n" came back with its newline.
451 {
452 6 local $/ = "\n";
453 6 chomp $stdout;
454 6 chomp $stderr;
455 }
456 6 ▶ return $stdout if $return eq 'stdout';
Branch: 1 branch
BranchTrueFalseTotal
if $return eq "stdout" 4 2 6
457 2 ▶ return $stderr if $return eq 'stderr';
Branch: 1 branch
BranchTrueFalseTotal
if $return eq "stderr" 1 1 2
458 1 return { exit => $exit, stdout => $stdout, stderr => $stderr }; # 'all', the only mode left
459 }
460  
461 5 ▶sub file2string {
Subroutine file2string: called CC=4 SCAR=13.9
Pod documented
462 5 my ($file) = @_;
463 # :raw, as the documentation promises: with the default layers, Windows
464 # perls read through :crlf, and "\r\n" came back as "\n".
465 5 ▶ open my $fh, '<:raw', $file or die "can't read $file: $!"; # was autodie
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $file or die "can't read ${file}: $!" 4 1 5
466 # open() succeeds on a directory on POSIX systems. Linux, OpenBSD and
467 # FreeBSD 13+ then fail the read with EISDIR, but NetBSD's read(2) returns
468 # the raw directory entries, so 0.0241 handed back binary garbage there
469 # (CPAN Testers report 52217fbc-dd66-11f1-9541-8d78add113b8, perl 5.42.3,
470 # amd64-netbsd-thread-multi). So a directory is refused by fstat, whatever
471 # read() would do; Windows never gets here, as its open() fails.
472 4 ▶ if (-d $fh) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $fh) 1 3 4
473 1 require POSIX;
474 1 $! = POSIX::EISDIR();
475 1 die "can't read $file: $!";
476 }
477 # readline returns undef only on an error -- an empty file reads as ''.
478 # Tested with // rather than through a lexical, which on perl 5.10.1 took
479 # a third copy of the file at return: a 200 MB file peaked at 575 MB,
480 # against 384 MB this way (5.44 is 195 MB either way, through
481 # copy-on-write).
482 3 ▶ return do { local $/; <$fh> } // die "can't read $file: $!";
Condition50%1/2
do { local $/; readline $fh } // die("can't read ${file}: $!")
l!l
30
MC/DC0%0/1
do { local $/; readline $fh } // die("can't read ${file}: $!")
do { local $/; readline $fh }
Truth table50%1/2
A
A= do { local $/; readline $fh }
Aresult
11
00
483 }
484  
485 31 ▶sub format_commas { # https://stackoverflow.com/questions/33442240/perl-printf-to-use-commas-as-thousands-separator
Subroutine format_commas: called CC=9 SCAR=22.0
Pod documented
486 31 my ($n, $format) = @_;
487 31 ▶ $format = '.%02d' unless defined $format;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $format 20 11 31
488 # '%.0u' is the documented way to ask for a whole number, but sprintf
489 # prints nothing for it only when the hundredths are 0: 1234.56 came out
490 # "1,23456". So '%.0u' is recognised here, rounds half up to a whole
491 # number, and prints no fraction at all.
492 31 my $whole = $format eq '%.0u';
493 # Infinity and NaN are returned as perl prints them. Run through the
494 # arithmetic below they came out "Inf.NaN", "-Inf.NaN" and "NaN.NaN".
495 # $n - $n is NaN for exactly these, and NaN is the one value not equal to
496 # itself.
497 31 my $diff = $n - $n;
498 31 ▶ return "$n" if $diff != $diff;
Branch: 1 branch
BranchTrueFalseTotal
if $diff != $diff 3 28 31
499 28 my $neg = $n < 0;
500 28 my $abs = abs $n;
501 28 my ($int, $cents);
502 28 ▶ if ($whole) {
Branch: 1 branch
BranchTrueFalseTotal
if ($whole) { } 11 17 28
503 11 $int = int($abs + .5);
504 11 $cents = 0;
505 } else {
506 17 $int = int $abs;
507 # int(100 * (.005 + frac)) is the original expression, and is exactly
508 # round-half-up to hundredths -- .005 * 100 is the +0.5 before truncation.
509 # Of the binary value, not the decimal the caller wrote: 1.005 is held as
510 # 1.00499999999999989... as a double, and gives 1.00, as README.md says.
511 # It is kept verbatim so no already-correct result shifts by a cent.
512 17 $cents = int(100 * (.005 + ($abs - $int)));
513 # ...but it can land on 100 (.999 rounds up to 1.00), which used to be
514 # printed straight into the fraction: 999999.999 came out "999,999.100".
515 # The carry has to go into the integer part instead.
516 17 ▶ if ($cents >= 100) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cents >= 100) 5 12 17
517 5 $int++;
518 5 $cents -= 100;
519 }
520 }
521 # Split off the sign and work on the magnitude: the old code fed a negative
522 # through int()/sprintf and produced "-1,234.-49" for -1234.5, and lost the
523 # sign entirely for -0.5. A value that rounds to zero stays unsigned, so
524 # -0.001 is "0.00" rather than "-0.00".
525 28 ▶ my $sign = ($neg && ($int || $cents)) ? '-' : '';
Branch: 1 branch
BranchTrueFalseTotal
$neg && ($int || $cents) ? : 5 23 28
Condition100%6/6
$neg and $int || $cents
!ll&&!rl&&r
2125
$int or $cents
l!l&&r!l&&!r
412
MC/DC100%3/3
$neg and $int || $cents
$neg $int $cents
Truth table100%4/4
A and B or C
A= $negB= $intC= $cents
ABCresult
0XX0
1000
11X1
1011
526 # '%.0f' rather than interpolating $int: a large magnitude stringifies in
527 # scientific notation, and the reverse/unpack grouping shredded that into
528 # "1e,+20" for 1e20.
529 28 my $digits = sprintf '%.0f', $int;
530 28 ▶ return $sign . reverse(join(',', unpack('(A3)*', reverse $digits))) . ($whole ? '' : sprintf($format, $cents));
Branch: 1 branch
BranchTrueFalseTotal
$whole ? : 11 17 28
531 }
532  
533 8 ▶sub json_file_to_ref {
Subroutine json_file_to_ref: called CC=6 SCAR=17.9
Pod documented
534 8 my ($json_filename) = @_;
535 8 ▶ die "$json_filename doesn't exist or isn't a file" unless -f $json_filename;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $json_filename 1 7 8
536 7 ▶ die "$json_filename has 0 size" if -s $json_filename == 0;
Branch: 1 branch
BranchTrueFalseTotal
if -s $json_filename == 0 1 6 7
537 6 ▶ open my $fh, '<:raw', $json_filename or die "can't read $json_filename: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $json_filename or die "can't read ${json_filename}: $!" 6 0 6
538 6 my $json = do { local $/; <$fh> }; # slurp; $/ restored immediately
539 6 close $fh;
540 # Python/NumPy emit bare NaN / Infinity / -Infinity, which are not valid
541 # JSON. Rewrite them to null (-> undef) only when they sit in JSON value
542 # position (after '[', ',' or ':', or as the whole document, which Python
543 # writes for json.dumps(float('nan')) and which used to reach decode_json
544 # unchanged and die there). That test alone also matched text
545 # inside a string -- "values: [1, NaN, 2]" became "values: [1, null, 2]"
546 # -- so the first alternative matches each whole string literal and
547 # (*SKIP)(*FAIL) resumes the scan after its closing quote.
548 #
549 # That scan is slow: on a 43 MB file of 300,000 records it took 2.1 s, to
550 # decode_json's 0.30 s (Cpanel::JSON::XS), measured 2026-11-09. The two
551 # index() calls that rule it out took 4.5 ms there, so a file with neither
552 # word, which is most of them, is not scanned at all.
553 6 ▶ $json =~ s/"(?:[^"\\]++|\\.)*+"(*SKIP)(*FAIL)|(?:\A|[\[,:])\s*\K-?(?:NaN|Infinity)(?=\s*(?:[,\]}]|\z))/null/gs
Branch: 1 branch
BranchTrueFalseTotal
if index($json, "NaN") != -1 or index($json, "Infinity") != -1 4 2 6
Condition100%3/3
index($json, "NaN") != -1 or index($json, "Infinity") != -1
l!l&&r!l&&!r
312
MC/DC100%2/2
index($json, "NaN") != -1 or index($json, "Infinity") != -1
index($json, "NaN") != -1 index($json, "Infinity") != -1
Truth table100%3/3
A or B
A= index($json, "NaN") != -1B= index($json, "Infinity") != -1
ABresult
1X1
011
000
554 if index($json, 'NaN') >= 0 || index($json, 'Infinity') >= 0;
555 6 require JSON::MaybeXS; # ~4.3 ms
556 6 return JSON::MaybeXS::decode_json($json);
557 }
558  
559 # These return *some* key/value from the hash, not a random one -- whichever
560 # pair the hash's internal iterator yields first.
561 #
562 # They used to be `foreach my $key (keys %{$hash}) { return $key }`, which is
563 # O(n): `keys` in list context materializes EVERY key into a temporary list,
564 # and then the loop throws all but the first away. On a 50,000-key hash that
565 # was 1.48 ms per call; via each() it is 0.15 us, ~10,000x faster.
566 #
567 # The bare `keys` in void context resets the iterator, so repeated calls keep
568 # returning the first pair instead of walking off the end of the hash. It is
569 # reset again after the each(), which would otherwise leave it one pair in, so
570 # that a caller's own `while (each %h)` afterwards skipped the first pair.
571 # The old `keys`-in-list-context version left it at the start, and so do these.
572 #
573 # Falling off a foreach also returned '' rather than undef in scalar context;
574 # each() on an empty hash returns an empty list, so these now yield a true
575 # undef, which is what t/random.t always asserted.
576 4 ▶sub random_key {
Subroutine random_key: called CC=1 SCAR=0.0
Pod documented
577 4 my ($hash) = @_;
578 4 keys %{ $hash }; # reset the iterator
579 4 my ($key) = each %{ $hash };
580 4 keys %{ $hash };
581 4 return $key;
582 }
583  
584 4 ▶sub random_value {
Subroutine random_value: called CC=1 SCAR=0.0
Pod documented
585 4 my ($hash) = @_;
586 4 keys %{ $hash }; # reset the iterator
587 4 my (undef, $value) = each %{ $hash };
588 4 keys %{ $hash };
589 4 return $value;
590 }
591  
592 9 ▶sub ref_to_json_file {
Subroutine ref_to_json_file: called CC=7 SCAR=19.5
Pod documented
593 9 my ($ref, $json_filename) = @_;
594 9 my $ref_json_filename = ref $json_filename;
595 9 ▶ unless ($ref_json_filename eq '') {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ref_json_filename eq "") 1 8 9
596 1 die "$json_filename isn't a scalar/string";
597 }
598 8 require JSON::MaybeXS;
599 # Encoded before the file is opened, because opening it empties it: up to
600 # 0.0242 a structure encode_json refused -- a cycle, a code reference --
601 # died after an existing file had already been truncated to nothing.
602 8 my $json = JSON::MaybeXS::encode_json($ref);
603 6 ▶ open my $fh, '>:raw', $json_filename # Write it unmangled
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $json_filename or die "can't write ${json_filename}: $!" 6 0 6
604 or die "can't write $json_filename: $!"; # was autodie
605 6 say $fh $json;
606 # A full disk shows up at close, when the buffer is flushed. Unchecked,
607 # perl up to 5.20 reported "Wrote" and returned the name of a truncated
608 # file, and later perls died with "unable to close filehandle" from the
609 # implicit close under FATAL warnings.
610 6 ▶ close $fh or die "can't write $json_filename: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or die "can't write ${json_filename}: $!" 5 1 6
611 # Colored by the rule structure()'s color => 'auto' follows. Up to 0.024
612 # it always was, so a log or a pipe that STDOUT went to got the escape
613 # codes too.
614 5 my $shown = $json_filename;
615 5 ▶ if (($ENV{CLICOLOR_FORCE} || -t STDOUT) && !$ENV{NO_COLOR}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"CLICOLOR_FORCE"} || -t STDOUT and not $ENV{"NO_COLOR"}) 1 4 5
Condition83%5/6
$ENV{"CLICOLOR_FORCE"} || -t STDOUT and not $ENV{"NO_COLOR"}
!ll&&!rl&&r
311
$ENV{"CLICOLOR_FORCE"} or -t STDOUT
l!l&&r!l&&!r
203
MC/DC66%2/3
$ENV{"CLICOLOR_FORCE"} || -t STDOUT and not $ENV{"NO_COLOR"}
$ENV{"CLICOLOR_FORCE"} -t STDOUT not $ENV{"NO_COLOR"}
Truth table60%3/5
A or B and not(C)
A= $ENV{"CLICOLOR_FORCE"}B= -t STDOUTC= not $ENV{"NO_COLOR"}
ABCresult
00X0
1X00
0100
1X11
0111
616 1 require Term::ANSIColor;
617 1 $shown = Term::ANSIColor::colored(['blue on_red'], $shown);
618 }
619 5 say "Wrote $shown";
620 5 return $json_filename;
621 }
622  
623 # ----------------------------------------------------------------------------
624 # structure(): print the *shape* of a data structure instead of its values.
625 #
626 # p() from Data::Printer shows you every value; when a 50,000-element array
627 # holds the same kind of record over and over, that is the wrong tool. This
628 # merges all elements of an array into ONE representative node, so you see the
629 # schema once. Keys absent from some of the merged records are flagged '?';
630 # values that disagree about their type become a UNION.
631 #
632 # Two entry points, mirroring DDP's own p()/np() split:
633 # st() - prototyped, so `st %hash` works like `p %hash`. Use this
634 # interactively.
635 # structure() - plain sub, takes a reference: structure(\%hash), or the
636 # return value of another call. Use this from other code.
637 #
638 # Scalar::Util and Term::ANSIColor are require'd in structure(), which st()
639 # also funnels through, so the per-value helpers below can call them fully
640 # qualified without re-checking %INC on every node. Scalar::Util is not loaded
641 # at `use` time because it drags in List::Util's XS bootstrap (~4 ms) and only
642 # this family ever touches it.
643  
644 11 my %STRUCTURE_COLOR = (
645 key => 'bold', # hash key names
646 opt => 'red', # the '?' optional marker
647 HASH => 'bold cyan',
648 ARRAY => 'bold yellow',
649 UNION => 'bold magenta',
650 elem => 'bright_black', # the '[*]' / '<alt>' / '(empty)' markers
651 class => 'bold white', # blessed package names
652 number => 'green',
653 string => 'bright_blue',
654 bool => 'bright_magenta',
655 null => 'bright_black',
656 CODE => 'yellow',
657 other => 'red', # anything unexpected
658 );
659  
660 200 ▶sub _structure_color {
Subroutine _structure_color: called CC=3 SCAR=16.5
661 200 my ($name, $text, $use_color) = @_;
662 200 ▶ return $text unless $use_color;
Branch: 1 branch
BranchTrueFalseTotal
unless $use_color 200 0 200
663 0 ▶ return Term::ANSIColor::colored([$STRUCTURE_COLOR{$name} // $STRUCTURE_COLOR{other}], $text);
Condition0%0/3
$STRUCTURE_COLOR{$name} // $STRUCTURE_COLOR{"other"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$STRUCTURE_COLOR{$name} // $STRUCTURE_COLOR{"other"}
$STRUCTURE_COLOR{$name} $STRUCTURE_COLOR{"other"}
Truth table0%0/3
A // B
A= $STRUCTURE_COLOR{$name}B= $STRUCTURE_COLOR{"other"}
ABresult
1X1
011
000
664 }
665  
666 # Classify one value. Blessed containers keep their package name so that
667 # Foo=HASH and a plain HASH don't get merged into the same node.
668 10112 ▶sub _structure_kind {
Subroutine _structure_kind: called CC=13 SCAR=29.6
669 10112 my ($v) = @_;
670 10112 ▶ return 'null' unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 1 10111 10112
671 10111 my $r = ref $v;
672 10111 ▶ return (Scalar::Util::looks_like_number($v) ? 'number' : 'string') if $r eq '';
Branch: 2 branches
BranchTrueFalseTotal
if $r eq "" 4 10107 10111
&Scalar::Util::looks_like_number($v) ? : 2 2 4
673 10107 ▶ if (my $class = Scalar::Util::blessed($v)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $class = builtin::blessed($v)) 3 10104 10107
674 3 ▶ return 'bool' if $class eq 'JSON::PP::Boolean' || $class eq 'Types::Serialiser::Boolean';
Branch: 1 branch
BranchTrueFalseTotal
if $class eq "JSON::PP::Boolean" or $class eq "Types::Serialiser::Boolean" 0 3 3
Condition33%1/3
$class eq "JSON::PP::Boolean" or $class eq "Types::Serialiser::Boolean"
l!l&&r!l&&!r
003
MC/DC0%0/2
$class eq "JSON::PP::Boolean" or $class eq "Types::Serialiser::Boolean"
$class eq "JSON::PP::Boolean" $class eq "Types::Serialiser::Boolean"
Truth table33%1/3
A or B
A= $class eq "JSON::PP::Boolean"B= $class eq "Types::Serialiser::Boolean"
ABresult
1X1
011
000
675 3 ▶ return 'Regexp' if $class eq 'Regexp';
Branch: 1 branch
BranchTrueFalseTotal
if $class eq "Regexp" 0 3 3
676 3 ▶ my $rt = Scalar::Util::reftype($v) // '';
Condition50%1/2
builtin::reftype($v) // ""
l!l
30
MC/DC0%0/1
builtin::reftype($v) // ""
builtin::reftype($v)
Truth table50%1/2
A
A= builtin::reftype($v)
Aresult
11
00
677 3 ▶ return "$class=$rt" if $rt eq 'HASH' || $rt eq 'ARRAY' || $rt eq 'SCALAR' || $rt eq 'REF';
Branch: 1 branch
BranchTrueFalseTotal
if $rt eq "HASH" or $rt eq "ARRAY" or $rt eq "SCALAR" or $rt eq "REF" 3 0 3
Condition33%3/9
$rt eq "HASH" or $rt eq "ARRAY" or $rt eq "SCALAR" or $rt eq "REF"
l!l&&r!l&&!r
300
$rt eq "HASH" or $rt eq "ARRAY" or $rt eq "SCALAR"
l!l&&r!l&&!r
300
$rt eq "HASH" or $rt eq "ARRAY"
l!l&&r!l&&!r
300
MC/DC0%0/4
$rt eq "HASH" or $rt eq "ARRAY" or $rt eq "SCALAR" or $rt eq "REF"
$rt eq "HASH" $rt eq "ARRAY" $rt eq "SCALAR" $rt eq "REF"
Truth table20%1/5
A or B or C or D
A= $rt eq "HASH"B= $rt eq "ARRAY"C= $rt eq "SCALAR"D= $rt eq "REF"
ABCDresult
1XXX1
01XX1
001X1
00011
00000
678 0 return $class;
679 }
680 10104 return $r; # HASH ARRAY SCALAR REF CODE GLOB
681 }
682  
683 # Merge a list of same-position values into a single structural node:
684 # { kind => 'hash', keys => { k => { node => .., optional => 0|1 } }, n, class }
685 # { kind => 'array', node => .., n => #instances, lens => [lengths], class }
686 # { kind => 'sref', node => .. } # \$x and \\$x
687 # { kind => 'leaf', types => { typename => 1, ... } }
688 # { kind => 'union', alts => { kindname => node } }
689 # $stack holds the refaddrs of the containers being described here or further
690 # out, so a self-referential structure terminates instead of recursing forever.
691 # $up is [ the batch of containers the values were taken from, the hash key
692 # they were taken from or undef ], which is where a value that is cut off
693 # finds the containers that hold it; see _structure_cut_label. $opt->{root}
694 # is the whole structure.
695 #
696 # The values arrive as $chunks, a list of array references whose elements,
697 # taken together, are the values. The elements of the arrays being merged are
698 # then described where they lie -- the arrays themselves are the chunks --
699 # rather than copied into one list, and values are copied only to split a
700 # union by kind. Copying at every level, as up to 0.024 did, took 413 MB on
701 # top of a 362 MB array of 300,000 five-key records, and 2.0 s; this takes
702 # 237 MB and 1.4 s (perl 5.44, 2026-11-09). Most of what is left is the
703 # copies of hash values, one list per key, and the cut-off guard's $stack.
704 86 ▶sub _structure_describe {
Subroutine _structure_describe: called CC=29 SCAR=33.7
705 86 my ($chunks, $opt, $depth, $stack, $up) = @_;
706 86 my %count; # kind => how many values are of that kind
707 86 for my $chunk (@{ $chunks }) {
708 # A plain scalar, the commonest value, is classified here rather than
709 # by a call to _structure_kind, which cost 0.3 s of the 1.7 s that
710 # 300,000 five-key records took. The answers are the same.
711 $count{ !defined $_ ? 'null'
712 : ref $_ ? _structure_kind($_)
713 92 ▶ : Scalar::Util::looks_like_number($_) ? 'number' : 'string' }++ for @{ $chunk };
Branch: 3 branches
BranchTrueFalseTotal
!defined($_) ? : 2 111 113
ref $_ ? : 73 38 111
&Scalar::Util::looks_like_number($_) ? : 30 8 38
714 }
715 86 my @kinds = sort keys %count;
716  
717 86 ▶ if (@kinds > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@kinds > 1) 3 83 86
718 3 my %by_kind;
719 3 for my $chunk (@{ $chunks }) {
720 5 push @{ $by_kind{ _structure_kind($_) } }, $_ for @{ $chunk };
721 }
722 return {
723 kind => 'union',
724 3 alts => { map { $_ => _structure_describe([$by_kind{$_}], $opt, $depth, $stack, $up) } @kinds },
725 };
726 }
727 83 ▶ my $k = $kinds[0] // 'null';
Condition50%1/2
$kinds[0] // "null"
l!l
830
MC/DC0%0/1
$kinds[0] // "null"
$kinds[0]
Truth table50%1/2
A
A= $kinds[0]
Aresult
11
00
728 83 my ($class, $reftype) = $k =~ /\A(.+)=(HASH|ARRAY|SCALAR|REF)\z/;
729 83 ▶ $reftype //= $k;
Condition66%2/3
$reftype //= $k
l!l&&r!l&&!r
1820
MC/DC0%0/2
$reftype //= $k
$reftype $k
Truth table66%2/3
A //= B
A= $reftypeB= $k
ABresult
1X1
011
000
730  
731 83 ▶ if ($reftype eq 'HASH' || $reftype eq 'ARRAY' || $reftype eq 'SCALAR' || $reftype eq 'REF') {
Branch: 1 branch
BranchTrueFalseTotal
if ($reftype eq "HASH" or $reftype eq "ARRAY" or $reftype eq "SCALAR" or $reftype eq "REF") 56 27 83
Condition100%9/9
$reftype eq "HASH" or $reftype eq "ARRAY" or $reftype eq "SCALAR" or $reftype eq "REF"
l!l&&r!l&&!r
50627
$reftype eq "HASH" or $reftype eq "ARRAY" or $reftype eq "SCALAR"
l!l&&r!l&&!r
49133
$reftype eq "HASH" or $reftype eq "ARRAY"
l!l&&r!l&&!r
341534
MC/DC100%4/4
$reftype eq "HASH" or $reftype eq "ARRAY" or $reftype eq "SCALAR" or $reftype eq "REF"
$reftype eq "HASH" $reftype eq "ARRAY" $reftype eq "SCALAR" $reftype eq "REF"
Truth table100%5/5
A or B or C or D
A= $reftype eq "HASH"B= $reftype eq "ARRAY"C= $reftype eq "SCALAR"D= $reftype eq "REF"
ABCDresult
1XXX1
01XX1
001X1
00011
00000
732 56 ▶ my $all = @{ $chunks } == 1 ? $chunks->[0] : [ map { @{ $_ } } @{ $chunks } ];
Branch: 1 branch
BranchTrueFalseTotal
@{$chunks;} == 1 ? : 55 1 56
733 # Drop anything we're already inside: its shape is an ancestor's shape.
734 # Copied only when there is something to drop.
735 69 my $fresh = (grep { $stack->{ Scalar::Util::refaddr($_) } } @{ $all })
736 56 ▶ ? [ grep { !$stack->{ Scalar::Util::refaddr($_) } } @{ $all } ]
Branch: 1 branch
BranchTrueFalseTotal
grep({$$stack{builtin::refaddr($_)};} @{$all;}) ? : 11 45 56
737 : $all;
738 56 ▶ return { kind => 'leaf', types => _structure_cut_label($all, $up, $opt) } unless @{ $fresh };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$fresh;} 11 45 56
739 45 ▶ if ($opt->{max_depth} && $depth >= $opt->{max_depth}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"max_depth"} and $depth >= $opt->{"max_depth"}) 2 43 45
Condition100%3/3
$opt->{"max_depth"} and $depth >= $opt->{"max_depth"}
!ll&&!rl&&r
3852
MC/DC100%2/2
$opt->{"max_depth"} and $depth >= $opt->{"max_depth"}
$opt->{"max_depth"} $depth >= $opt->{"max_depth"}
Truth table100%3/3
A and B
A= $opt->{"max_depth"}B= $depth >= $opt->{"max_depth"}
ABresult
0X0
100
111
740 2 return { kind => 'leaf', types => { '(...)' => 1 } };
741 }
742 43 local @{ $stack }{ map { Scalar::Util::refaddr($_) } @{ $fresh } } = (1) x @{ $fresh };
743  
744 43 ▶ if ($reftype eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if ($reftype eq 'HASH') { } 23 20 43
elsif ($reftype eq 'ARRAY') { } 14 6 20
745 # Each hash puts one value under each of its keys, so a key whose
746 # list is shorter than @$fresh is missing from some of them.
747 23 my %vals; # key => [ its value in each hash that has it ]
748 23 for my $h (@{ $fresh }) {
749 33 push @{ $vals{$_} }, $h->{$_} for keys %{ $h };
750 }
751 # A wide hash used as a dictionary has no interesting key names:
752 # merge every value into one representative entry instead.
753 23 ▶ if ($opt->{hash_max} && keys %vals > $opt->{hash_max}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"hash_max"} and keys %vals > $opt->{"hash_max"}) 1 22 23
Condition66%2/3
$opt->{"hash_max"} and keys %vals > $opt->{"hash_max"}
!ll&&!rl&&r
0221
MC/DC50%1/2
$opt->{"hash_max"} and keys %vals > $opt->{"hash_max"}
$opt->{"hash_max"} keys %vals > $opt->{"hash_max"}
Truth table66%2/3
A and B
A= $opt->{"hash_max"}B= keys %vals > $opt->{"hash_max"}
ABresult
0X0
100
111
754 return {
755 kind => 'hash',
756 class => $class,
757 1 n => scalar @{ $fresh },
758 wide => scalar keys %vals,
759 keys => { '*' => {
760 node => _structure_describe([values %vals], $opt, $depth + 1, $stack, [$fresh]),
761 optional => 0,
762 }},
763 };
764 }
765 22 my %out;
766 22 for my $key (keys %vals) {
767 $out{$key} = {
768 node => _structure_describe([$vals{$key}], $opt, $depth + 1, $stack, [$fresh, $key]),
769 37 ▶ optional => (@{ $vals{$key} } < @{ $fresh } ? 1 : 0),
Branch: 1 branch
BranchTrueFalseTotal
@{$vals{$key};} < @{$fresh;} ? : 11 26 37
770 };
771 }
772 22 return { kind => 'hash', class => $class, n => scalar @{ $fresh }, keys => \%out };
773 }
774 elsif ($reftype eq 'ARRAY') {
775 14 my @lens = map { scalar @{ $_ } } @{ $fresh };
776 return {
777 kind => 'array',
778 class => $class,
779 16 node => ((grep { $_ } @lens) ? _structure_describe($fresh, $opt, $depth + 1, $stack, [$fresh]) : undef),
780 14 ▶ n => scalar @{ $fresh },
Branch: 1 branch
BranchTrueFalseTotal
grep({$_;} @lens) ? : 14 0 14
781 lens => \@lens,
782 };
783 }
784 return { # SCALAR / REF
785 kind => 'sref',
786 class => $class,
787 6 node => _structure_describe([[ map { ${ $_ } } @{ $fresh } ]], $opt, $depth + 1, $stack, [$fresh]),
788 };
789 }
790 27 return { kind => 'leaf', types => { $k => 1 } };
791 }
792  
793 # The leaf types for a place whose every value was cut off because it is
794 # already being described further out. Up to 0.0242 that was always
795 # '(cycle)', but a value shared by two places, such as $b in [$a, $b] with
796 # $a->{child} = $b, was cut just the same and so was called a cycle when the
797 # data had none. Following it instead, through every path, is exact but can
798 # grow without bound: a tree whose n nodes each list their siblings has
799 # roughly n**3 paths through them, against the n steps the cut-off takes. So
800 # the cut stays and only its label changes.
801 #
802 # A reference X held by a container P lies on a loop exactly when X leads
803 # back to P, that is, when they share a strongly connected component of the
804 # whole structure's graph. So each reference to a cut value from this place
805 # -- under the hash key it came from, when it came from one, because P may
806 # hold X under another key as part of a different loop -- is '(cycle)' or
807 # '(shown above)', and a place with both kinds shows both. The components
808 # are found once per call to structure(), and only once something is cut.
809 11 ▶sub _structure_cut_label {
Subroutine _structure_cut_label: called CC=9 SCAR=22.2
810 11 my ($all, $up, $opt) = @_;
811 11 my ($from, $key) = @{ $up };
812 11 ▶ my $comp = $opt->{scc} //= _structure_scc($opt->{root});
Condition66%2/3
$opt->{"scc"} //= _structure_scc($opt->{"root"})
l!l&&r!l&&!r
380
MC/DC0%0/2
$opt->{"scc"} //= _structure_scc($opt->{"root"})
$opt->{"scc"} _structure_scc($opt->{"root"})
Truth table66%2/3
A //= B
A= $opt->{"scc"}B= _structure_scc($opt->{"root"})
ABresult
1X1
011
000
813 11 my %cut = map { Scalar::Util::refaddr($_) => 1 } @{ $all };
814 11 my %types;
815 11 for my $p (@{ $from }) {
816 18 my $pc = $comp->{ Scalar::Util::refaddr($p) };
817 2 ▶ my @held = !defined $key ? @{ _structure_kids($p) }
Branch: 1 branch
BranchTrueFalseTotal
exists $p->{$key} ? : 10 6 16
818 18 ▶ : exists $p->{$key} ? ($p->{$key})
Branch: 1 branch
BranchTrueFalseTotal
!defined($key) ? : 2 16 18
819 : ();
820 18 for my $kid (@held) {
821 12 ▶ next unless ref $kid && $cut{ Scalar::Util::refaddr($kid) };
Branch: 1 branch
BranchTrueFalseTotal
unless ref $kid and $cut{builtin::refaddr($kid)} 0 12 12
Condition33%1/3
ref $kid and $cut{builtin::refaddr($kid)}
!ll&&!rl&&r
0012
MC/DC0%0/2
ref $kid and $cut{builtin::refaddr($kid)}
ref $kid $cut{builtin::refaddr($kid)}
Truth table33%1/3
A and B
A= ref $kidB= $cut{builtin::refaddr($kid)}
ABresult
0X0
100
111
822 12 ▶ $types{ $comp->{ Scalar::Util::refaddr($kid) } == $pc ? '(cycle)' : '(shown above)' } = 1;
Branch: 1 branch
BranchTrueFalseTotal
$$comp{builtin::refaddr($kid)} == $pc ? : 9 3 12
823 }
824 }
825 11 return \%types;
826 }
827  
828 # The containers $v holds directly, as _structure_describe descends into them:
829 # hash values, array elements and the referent of a scalar reference.
830 5027 ▶sub _structure_kids {
Subroutine _structure_kids: called CC=4 SCAR=13.9
831 5027 my ($v) = @_;
832 5027 my $rt = Scalar::Util::reftype($v);
833 15036 ▶ return [ grep { ref $_ && _structure_kind($_) =~ /(?:\A|=)(?:HASH|ARRAY|SCALAR|REF)\z/ }
Branch: 1 branch
BranchTrueFalseTotal
$rt eq 'HASH' ? : 5011 16 5027
Condition66%2/3
ref $_ && _structure_kind($_) =~ /(?:\A|=)(?:HASH|ARRAY|SCALAR|REF)\z/
!ll&&!rl&&r
5006010030
MC/DC50%1/2
ref $_ && _structure_kind($_) =~ /(?:\A|=)(?:HASH|ARRAY|SCALAR|REF)\z/
ref $_ _structure_kind($_) =~ /(?:\A|=)(?:HASH|ARRAY|SCALAR|REF)\z/
Truth table66%2/3
A && B
A= ref $_B= _structure_kind($_) =~ /(?:\A|=)(?:HASH|ARRAY|SCALAR|REF)\z/
ABresult
0X0
100
111
834 5027 ▶ $rt eq 'HASH' ? values %{ $v } : $rt eq 'ARRAY' ? @{ $v } : ${ $v } ];
Branch: 1 branch
BranchTrueFalseTotal
$rt eq 'ARRAY' ? : 14 2 16
835 }
836  
837 # Strongly connected components of the containers reachable from $root, as
838 # { refaddr => component number }, by Tarjan's algorithm (R. E. Tarjan, "Depth-
839 # first search and linear graph algorithms", SIAM J. Comput. 1(2), 1972). It
840 # runs on an explicit stack rather than by recursion, because a linked list a
841 # few thousand nodes long would otherwise die of "Deep recursion" under FATAL
842 # warnings.
843 #
844 # Two hashes rather than the textbook's four, which on 300,000 records took
845 # 95 MB: %low holds exactly the nodes on Tarjan's stack, so it doubles as the
846 # on-stack set, and each node's entry in %num is its visiting order until its
847 # component is found, then its component number.
848 8 ▶sub _structure_scc {
Subroutine _structure_scc: called CC=11 SCAR=24.0
849 8 my ($root) = @_;
850 8 my (%num, %low, @stack, @frames);
851 8 my ($next, $ncomp) = (0, 0);
852 8 for my $w (@{ _structure_kids([$root]) }) { # [$root]: so that a $root that is no container is skipped
853 8 my $addr = Scalar::Util::refaddr($w);
854 8 $num{$addr} = $low{$addr} = $next++;
855 8 push @stack, $addr;
856 8 push @frames, [ $addr, _structure_kids($w), 0 ]; # refaddr, its containers, how many visited
857 }
858 8 ▶ while (@frames) {
Branch: 1 branch
BranchTrueFalseTotal
if (@frames) 15037 8 15045
859 15037 my $f = $frames[-1];
860 15037 my $addr = $f->[0];
861 15037 ▶ if ($f->[2] < @{ $f->[1] }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($f->[2] < @{$f->[1];}) 10020 5017 15037
862 10020 my $w = $f->[1][ $f->[2]++ ];
863 10020 my $kaddr = Scalar::Util::refaddr($w);
864 10020 ▶ if (!exists $num{$kaddr}) {
Branch: 2 branches
BranchTrueFalseTotal
if (not exists $num{$kaddr}) { } 5009 5011 10020
elsif (exists $low{$kaddr} and $num{$kaddr} < $low{$addr}) { } 2508 2507 5015
865 5009 $num{$kaddr} = $low{$kaddr} = $next++;
866 5009 push @stack, $kaddr;
867 5009 push @frames, [ $kaddr, _structure_kids($w), 0 ];
868 ▶ } elsif (exists $low{$kaddr} && $num{$kaddr} < $low{$addr}) {
Condition100%3/3
exists $low{$kaddr} and $num{$kaddr} < $low{$addr}
!ll&&!rl&&r
424992508
MC/DC100%2/2
exists $low{$kaddr} and $num{$kaddr} < $low{$addr}
exists $low{$kaddr} $num{$kaddr} < $low{$addr}
Truth table100%3/3
A and B
A= exists $low{$kaddr}B= $num{$kaddr} < $low{$addr}
ABresult
0X0
100
111
869 2508 $low{$addr} = $num{$kaddr};
870 }
871 10020 next;
872 }
873 5017 pop @frames;
874 5017 my $low = $low{$addr};
875 5017 ▶ if ($low == $num{$addr}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($low == $num{$addr}) 16 5001 5017
876 16 my $kaddr;
877 16 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
$kaddr == $addr or do { do { $kaddr = pop @stack; delete $low{$kaddr}; $num{$kaddr} = $ncomp } } 16 5001 5017
878 5017 $kaddr = pop @stack;
879 5017 delete $low{$kaddr};
880 5017 $num{$kaddr} = $ncomp;
881 } until $kaddr == $addr;
882 16 $ncomp++;
883 }
884 5017 ▶ if (@frames) {
Branch: 1 branch
BranchTrueFalseTotal
if (@frames) 5009 8 5017
885 5009 my $p = $frames[-1][0];
886 5009 ▶ $low{$p} = $low if $low < $low{$p};
Branch: 1 branch
BranchTrueFalseTotal
if $low < $low{$p} 4996 13 5009
887 }
888 }
889 8 return \%num;
890 }
891  
892 14 ▶sub _structure_array_desc {
Subroutine _structure_array_desc: called CC=6 SCAR=17.9
893 14 my ($node, $c) = @_;
894 14 my @lens = @{ $node->{lens} };
895 14 my ($min, $max) = ($lens[0], $lens[0]);
896 14 ▶ for (@lens) { $min = $_ if $_ < $min; $max = $_ if $_ > $max }
Branch: 2 branches
BranchTrueFalseTotal
if $_ < $min 0 16 16
if $_ > $max 1 15 16
897 14 ▶ my $range = $min == $max ? $min : "$min-$max";
Branch: 1 branch
BranchTrueFalseTotal
$min == $max ? : 13 1 14
898 14 my $out = $c->('ARRAY', "ARRAY[$range]");
899 14 ▶ $out .= " (from $node->{n} instances)" if $node->{n} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $node->{"n"} > 1 1 13 14
900 14 return $out;
901 }
902  
903 86 ▶sub _structure_render {
Subroutine _structure_render: called CC=17 SCAR=28.4
904 86 my ($label, $node, $indent, $opt, $c, $lines) = @_;
905 86 ▶ my $pad = (' ' x $indent) . ($label // '');
Condition100%2/2
$label // ""
l!l
6620
MC/DC100%1/1
$label // ""
$label
Truth table100%2/2
A
A= $label
Aresult
11
00
906 86 ▶ my $class = defined $node->{class} ? $c->('class', "$node->{class}=") : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $node->{'class'} ? : 1 85 86
907  
908 86 ▶ if ($node->{kind} eq 'hash') {
Branch: 4 branches
BranchTrueFalseTotal
if ($node->{'kind'} eq 'hash') { } 23 63 86
elsif ($node->{'kind'} eq 'array') { } 14 49 63
elsif ($node->{'kind'} eq 'sref') { } 6 43 49
elsif ($node->{'kind'} eq 'union') { } 3 40 43
909 23 my @k = sort keys %{ $node->{keys} };
910 23 ▶ my $count = $node->{wide} // scalar @k;
Condition100%2/2
$node->{"wide"} // scalar @k
l!l
122
MC/DC100%1/1
$node->{"wide"} // scalar @k
$node->{"wide"}
Truth table100%2/2
A
A= $node->{"wide"}
Aresult
11
00
911 23 ▶ push @{ $lines }, $pad . $class . $c->('HASH', "HASH{$count}")
Branch: 2 branches
BranchTrueFalseTotal
$node->{'n'} > 1 ? : 6 17 23
$node->{'wide'} ? : 1 22 23
912 . ($node->{n} > 1 ? " (from $node->{n} instances)" : '')
913 23 . ($node->{wide} ? ' ' . $c->('elem', '(keys merged)') : '');
914 23 for my $key (@k) {
915 38 my $entry = $node->{keys}{$key};
916 my $name = ($key eq '*' && $node->{wide})
917 ? $c->('elem', '<*>') . ': '
918 38 ▶ : $c->('key', $key) . ($entry->{optional} ? $c->('opt', '?') : '') . ': ';
Branch: 2 branches
BranchTrueFalseTotal
$key eq '*' && $node->{'wide'} ? : 1 37 38
$entry->{'optional'} ? : 11 26 37
Condition66%2/3
$key eq "*" and $node->{"wide"}
!ll&&!rl&&r
3701
MC/DC50%1/2
$key eq "*" and $node->{"wide"}
$key eq "*" $node->{"wide"}
Truth table66%2/3
A and B
A= $key eq "*"B= $node->{"wide"}
ABresult
0X0
100
111
919 38 _structure_render($name, $entry->{node}, $indent + 1, $opt, $c, $lines);
920 }
921 }
922 elsif ($node->{kind} eq 'array') {
923 14 push @{ $lines }, $pad . $class . _structure_array_desc($node, $c);
924 14 ▶ if ($node->{node}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node->{'node'}) { } 14 0 14
925 14 _structure_render($c->('elem', '[*]') . ': ', $node->{node}, $indent + 1, $opt, $c, $lines);
926 } else {
927 0 push @{ $lines }, (' ' x ($indent + 1)) . $c->('elem', '(empty)');
928 }
929 }
930 elsif ($node->{kind} eq 'sref') { # \$x: stay on the same line, no extra indent level
931 # The '\ ' joins the label rather than the pad, and $indent passes
932 # through unchanged, so whatever the referent holds is still indented
933 # from this line. Passing $pad with indent 0 put the line right but
934 # dropped the referent's own children back to depth 1.
935 6 ▶ _structure_render(($label // '') . $class . $c->('elem', '\\') . ' ', $node->{node}, $indent, $opt, $c, $lines);
Condition100%2/2
$label // ""
l!l
42
MC/DC100%1/1
$label // ""
$label
Truth table100%2/2
A
A= $label
Aresult
11
00
936 }
937 elsif ($node->{kind} eq 'union') {
938 3 push @{ $lines }, $pad . $c->('UNION', 'UNION');
939 3 for my $alt (sort keys %{ $node->{alts} }) {
940 8 _structure_render($c->('elem', "<$alt>") . ' ', $node->{alts}{$alt}, $indent + 1, $opt, $c, $lines);
941 }
942 }
943 else { # leaf
944 40 push @{ $lines }, $pad . join($c->('elem', '|'),
945 40 map { $c->($_, $_) } sort keys %{ $node->{types} });
946 }
947 86 return;
948 }
949  
950 21 ▶sub structure {
Subroutine structure: called CC=14 SCAR=32.8
Pod documented
951 21 my ($ref, %args) = @_;
952 21 my %opt = (
953 output => 'stdout', # 'stdout' | 'stderr' | 'string' (string: return it, print nothing)
954 color => 'auto', # 'auto' | 1 | 0
955 max_depth => 0, # 0 = unlimited
956 hash_max => 32, # hashes wider than this collapse to one '<*>' entry; 0 = never
957 as => undef, # optional header line, like DDP's "as"
958 %args,
959 );
960 21 my %allowed = map { $_ => 1 } qw(output color max_depth hash_max as);
961 21 ▶ if (my @bad = grep { !$allowed{$_} } keys %opt) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@bad) = grep({not $allowed{$_};} keys %opt)) 0 21 21
962 0 die "Unrecognized arguments: @bad\nAccepted args: " . join(', ', sort keys %allowed);
963 }
964 # undef as in dir(): this message, not "Use of uninitialized value".
965 21 for my $name (qw(output color)) {
966 42 ▶ die "$name must be defined" unless defined $opt{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $opt{$name} 1 41 42
967 }
968 20 ▶ die "output must be one of stdout, stderr, string" if $opt{output} !~ m/\A(stdout|stderr|string)\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $opt{"output"} =~ /\A(stdout|stderr|string)\z/ 0 20 20
969  
970 20 require Scalar::Util; # ~4 ms (List::Util XS bootstrap); see header note
971  
972 20 ▶ my $fh = $opt{output} eq 'stderr' ? \*STDERR : \*STDOUT;
Branch: 1 branch
BranchTrueFalseTotal
$opt{'output'} eq 'stderr' ? : 0 20 20
973 my $use_color = $opt{color} eq 'auto'
974 ? ((($ENV{CLICOLOR_FORCE} || ($opt{output} ne 'string' && -t $fh)) && !$ENV{NO_COLOR}) ? 1 : 0)
975 20 ▶ : $opt{color};
Branch: 2 branches
BranchTrueFalseTotal
$opt{'color'} eq 'auto' ? : 0 20 20
($ENV{'CLICOLOR_FORCE'} || $opt{'output'} ne 'string' && -t $fh) && !$ENV{'NO_COLOR'} ? : 0 0 0
Condition0%0/9
$ENV{"CLICOLOR_FORCE"} || $opt{"output"} ne "string" && -t $fh and not $ENV{"NO_COLOR"}
!ll&&!rl&&r
000
$ENV{"CLICOLOR_FORCE"} or $opt{"output"} ne "string" and -t $fh
l!l&&r!l&&!r
000
$opt{"output"} ne "string" and -t $fh
!ll&&!rl&&r
000
MC/DC0%0/4
$ENV{"CLICOLOR_FORCE"} || $opt{"output"} ne "string" && -t $fh and not $ENV{"NO_COLOR"}
$ENV{"CLICOLOR_FORCE"} $opt{"output"} ne "string" -t $fh not $ENV{"NO_COLOR"}
Truth table0%0/6
A or B and C and not(D)
A= $ENV{"CLICOLOR_FORCE"}B= $opt{"output"} ne "string"C= -t $fhD= not $ENV{"NO_COLOR"}
ABCDresult
00XX0
010X0
1XX00
01100
1XX11
01111
976 20 ▶ require Term::ANSIColor if $use_color; # ~0.8 ms, skipped entirely when piping
Branch: 1 branch
BranchTrueFalseTotal
if $use_color 0 20 20
977 20 ▶ my $c = sub { _structure_color($_[0], $_[1], $use_color) };
Subroutine __ANON__: called CC=1 SCAR=0.0
978  
979 20 my @lines;
980 20 ▶ push @lines, $c->('key', $opt{as}) if defined $opt{as};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt{"as"} 0 20 20
981 20 _structure_render(undef, _structure_describe([[$ref]], { %opt, root => $ref }, 0, {}, [[]]), 0, \%opt, $c, \@lines);
982 20 my $out = join("\n", @lines) . "\n";
983 0 ▶ print {$fh} $out unless $opt{output} eq 'string';
Branch: 1 branch
BranchTrueFalseTotal
unless $opt{"output"} eq "string" 0 20 20
984 20 return $out;
985 }
986  
987 # st(): structure() with DDP's calling convention, so you can write
988 #
989 # st %hash; st @array; st $ref; st %hash, max_depth => 2;
990 #
991 # instead of backslashing by hand. The \[@$%&] prototype makes perl pass a
992 # reference to the caller's variable, which is the whole trick -- but it also
993 # means the argument must BE a variable: st(\%h), st({...}) and
994 # st(func()) are compile-time errors, exactly as they are for DDP's p().
995 # Call structure() directly in those cases.
996 #
997 # NOTE: the obvious short name 's' is impossible. perl's tokenizer resolves a
998 # bare 's' to the substitution operator before it ever looks for a sub of that
999 # name, so `s $ref` dies with "Substitution pattern not terminated" and even
1000 # `s($ref)` is parsed as s(pat)(repl). Only `&s($ref)` would work, which
1001 # defeats the point. Hence 'st'.
1002 1 ▶sub st (\[@$%&];%) {
Subroutine st: called CC=3 SCAR=13.3
Pod documented
1003 1 my ($item, @args) = @_;
1004 # `st %h` / `st @a` / `st &c` hand us the HASH/ARRAY/CODE ref directly, but
1005 # `st $x` hands us a ref to the scalar $x -- one layer more than we want.
1006 # The prototype rejects everything except a plain variable, so a SCALAR/REF
1007 # here is always that added layer: peel exactly one. `st $hashref` then
1008 # describes the hash, and `my $x = 42; st $x` prints 'number', not '\ number'.
1009 0 ▶ my $ref = (ref($item) eq 'SCALAR' || ref($item) eq 'REF') ? ${ $item } : $item;
Branch: 1 branch
BranchTrueFalseTotal
ref $item eq 'SCALAR' || ref $item eq 'REF' ? : 0 1 1
Condition33%1/3
ref $item eq "SCALAR" or ref $item eq "REF"
l!l&&r!l&&!r
001
MC/DC0%0/2
ref $item eq "SCALAR" or ref $item eq "REF"
ref $item eq "SCALAR" ref $item eq "REF"
Truth table33%1/3
A or B
A= ref $item eq "SCALAR"B= ref $item eq "REF"
ABresult
1X1
011
000
1010 1 return structure($ref, @args);
1011 }
1012  
1013 11 1;
1014 # from md2pod.pl πατερ ημων ο εν τοις ουρανοις, ἁγιασθήτω τὸ ὄνομά σου
1015 =encoding utf8
1016  
1017 =head1 NAME
1018  
1019 Cn::Util - Small everyday helpers: directory listing, shell commands, JSON files, number formatting, and data-structure shapes
1020  
1021 =head1 Synopsis
1022  
1023 use Cn::Util;
1024
1025 my @scripts = dir(dir => '.', regex => '\.pl$', recursive => 1);
1026 my $branch = execute('git rev-parse --abbrev-ref HEAD', 'stdout');
1027 my $text = file2string('notes.txt');
1028 print format_commas(1234567.891), "\n"; # 1,234,567.89
1029
1030 my $data = json_file_to_ref('results.json');
1031 ref_to_json_file($data, 'copy.json');
1032
1033 st $data; # print the shape of $data, not its values
1034 p $data; # Data::Printer's p(), loaded on first use
1035  
1036 =head1 Description
1037  
1038 C<Cn::Util> is a collection of the functions I reach for in nearly every script: listing a directory with file tests and a regex, running a shell command and keeping its output, slurping a file, reading and writing JSON, putting commas in a number, and seeing the I<shape> of a large data structure without scrolling through every value in it.
1039  
1040 Loading it is meant to be cheap. Everything that is not needed to compile the caller is loaded the first time a function needs it, so a script that only calls C<format_commas> does not pay for C<JSON::MaybeXS>, C<Capture::Tiny> or C<Data::Printer>.
1041  
1042 =head2 What C<use Cn::Util> does
1043  
1044 Besides exporting the ten functions below, C<use Cn::Util> does three things to the file and package that loads it:
1045  
1046 =over
1047  
1048 =item * It turns on C<autodie ':default'> in that file, from the C<use> line onward, so a bare C<open> or C<close> that fails dies with a message rather than returning false.
1049  
1050 =item * It gives that package C<p> and C<np> from C<Data::Printer> (C<DDP>). They are stubs until first called, so C<DDP> is loaded only by a script that prints something. A C<p> or C<np> the package already has, such as one from an earlier C<use DDP>, is left alone.
1051  
1052 =item * It loads C<Devel::Confess>, which is process-wide: every C<die> and C<warn> in the program carries a stack trace.
1053  
1054 =back
1055  
1056 C<use Cn::Util ();> imports nothing and skips the first two; C<Devel::Confess> is still loaded. C<use Cn::Util 'format_commas';> imports only the names given, and still does all three.
1057  
1058 =head1 Functions
1059  
1060 All functions are exported by default.
1061  
1062 =head2 dir
1063  
1064 my @files = dir(dir => '/data', regex => '\.csv$');
1065 my @tree = dir(dir => '/data', regex => '\.csv$', recursive => 1, cpu => 8);
1066 dir(dir => '/data', recursive => 1, on_match => sub { say $_[0] });
1067  
1068 Returns the paths under C<dir> whose base name matches C<regex> and that pass every file test in C<tests>. The paths are C<dir> joined to the entry with C</>; with the default C<< dir =E<gt> '.' >>, the leading C<./> is left off. C<.> and C<..> are never returned.
1069  
1070 It takes these named arguments:
1071  
1072 =over
1073  
1074 =item * C<dir> (default C<.>): The directory to list. Trailing slashes are removed, but C</> stays C</>. A C<dir> that is a symbolic link to a directory is listed through the link, recursively or not.
1075  
1076 =item * C<regex> (default C<.>): A pattern the base name must match, given as a string or a C<qr//>. An invalid pattern dies, naming it.
1077  
1078 =item * C<tests> (default C<f>): One or more of perl's file tests, as letters: C<rwxoRWXOezsfdlpSbcugkTB>. Every one must pass. C<'d'> lists directories; C<''> applies no test at all.
1079  
1080 =item * C<recursive> (default C<0>): C<1> descends into subdirectories, without following symbolic links.
1081  
1082 =item * C<cpu> (default C<1>): For a recursive listing, the number of worker processes (through C<Parallel::ForkManager>). Ignored when C<recursive> is C<0>.
1083  
1084 =item * C<on_match> (no default): A code reference called with each path as it is found; C<dir> then returns an empty list, so a very large tree is never held in memory.
1085  
1086 =back
1087  
1088 The file tests share one C<stat> per path, so asking for four of them costs no more than asking for one. C<-l> is checked first, with C<lstat>.
1089  
1090 With C<cpu> greater than 1, C<dir> walks the tree breadth-first until one level holds four directories per worker, then shares those directories out. The results are the same as a serial walk, in a different order. C<on_match> still runs in the calling process, so it can change the caller's variables, but it is called once a worker's whole batch arrives rather than as each file is found. A worker leaves without running the program's C<END> blocks or destructors, except on Windows, where it is a thread of the calling process.
1091  
1092 An unknown argument, an undefined C<tests>, C<dir>, C<regex> or C<cpu>, a letter that is not a file test, a C<cpu> that is not a positive integer, an C<on_match> that is not a code reference, and a directory that cannot be opened, whether C<dir> itself or one a recursive listing meets, all die.
1093  
1094 =head2 execute
1095  
1096 my $exit = execute('make test'); # 0, or dies
1097 my $out = execute('git log -1 --format=%H', 'stdout');
1098 my $err = execute('perl -c script.pl', 'stderr');
1099 my $all = execute('ls /nonexistent', 'all', 0); # does not die
1100 # $all = { exit => 512, stdout => '', stderr => "ls: cannot access ..." }
1101  
1102 Runs C<$cmd> through the shell with C<system>, capturing its standard output and standard error with C<Capture::Tiny>. The second argument says what to return:
1103  
1104 =over
1105  
1106 =item * C<exit> (the default): the wait status, C<$?> -- 0 for success, 256 for C<exit 1>
1107  
1108 =item * C<stdout>: standard output, chomped
1109  
1110 =item * C<stderr>: standard error, chomped
1111  
1112 =item * C<all>: a hash reference with C<exit>, C<stdout> and C<stderr>
1113  
1114 =back
1115  
1116 The third argument, C<$die>, is true by default: a command that exits non-zero prints its exit status, standard output and standard error to C<STDERR> and dies. Pass a false value, such as 0, to have the status returned instead.
1117  
1118 The command's standard input is an empty pipe. A command that would prompt -- C<rm> on a write-protected file, C<cp -i> -- reads end-of-file and declines rather than waiting, unseen, for an answer. The caller's C<STDIN> is not touched, so input it has already read ahead is still there afterwards, even when C<execute> dies.
1119  
1120 =head2 file2string
1121  
1122 my $text = file2string('notes.txt');
1123  
1124 Returns the whole of a file as one string, read without any decoding layer. A file that cannot be opened or read, such as a directory, dies, naming it.
1125  
1126 =head2 format_commas
1127  
1128 format_commas(1234567.891); # '1,234,567.89'
1129 format_commas(1234567, '%.0u'); # '1,234,567'
1130 format_commas(999999.999); # '1,000,000.00'
1131 format_commas(-0.5); # '-0.50'
1132 format_commas(1e20); # '100,000,000,000,000,000,000.00'
1133  
1134 Puts a comma between each group of three digits of the integer part and appends the hundredths, rounded half up. The second argument is the C<sprintf> format the hundredths are printed with, C<'.%02d'> by default; C<'%.0u'> rounds half up to a whole number and prints no fraction. Rounding that carries into the integer part does so (C<0.999> is C<1.00>), a negative number keeps its sign, a number that rounds to zero has none, and a large number is grouped as digits rather than printed in exponent form. Infinity and NaN are returned as perl prints them.
1135  
1136 What is rounded is the number perl holds, which is binary, not the decimal written in the source. Most decimal fractions have no exact binary form, so a value written as exactly half a cent is stored a little above or below it, and rounds accordingly: C<1.005> is held as 1.00499999999999989... where perl's numbers are doubles, so C<format_commas(1.005)> is C<'1.00'>, and likewise C<2.675> gives C<'2.67'> and C<9.995> gives C<'9.99'>, which is also what C<sprintf('%.2f', ...)> prints. Money that must round by its decimal digits should be kept in whole cents, or in C<Math::BigFloat>.
1137  
1138 =head2 json_file_to_ref
1139  
1140 my $ref = json_file_to_ref('results.json');
1141  
1142 Reads a JSON file and returns the decoded data, through C<JSON::MaybeXS>. Python's C<json> module and NumPy write C<NaN>, C<Infinity> and C<-Infinity> as bare words, which are not JSON; where one of those stands as a value, or is the whole document, it is read as C<null>, so it becomes C<undef>. The same words inside a string are left alone. A file that does not exist, or is empty, dies.
1143  
1144 =head2 ref_to_json_file
1145  
1146 ref_to_json_file($data, 'results.json'); # prints "Wrote results.json"
1147  
1148 Writes a data structure to a file as JSON, through C<JSON::MaybeXS>, prints C<Wrote> and the file name, and returns the file name. The name is colored by the rule C<structure>'s C<< color =E<gt> 'auto' >> follows: when C<STDOUT> is a terminal, or C<CLICOLOR_FORCE> is set, and C<NO_COLOR> is not. The file name must be a plain string; a reference dies, and so does a write that fails, such as on a full disk, before anything is printed. A structure that cannot be encoded, such as one holding a code reference or a reference to itself, dies before the file is opened, so an existing file of that name is left as it was.
1149  
1150 =head2 random_key, random_value
1151  
1152 my $key = random_key(\%hash);
1153 my $value = random_value(\%hash);
1154  
1155 Return one key, or one value, of a hash -- whichever pair perl's hash iterator yields first, which is quick no matter how big the hash is. This is I<any> key, not a randomly chosen one: the same hash returns the same pair each time. It is useful for looking at one record of a hash of records. An empty hash returns C<undef>.
1156  
1157 Both reset the hash's iterator, so do not call them on a hash in the middle of an C<each> loop.
1158  
1159 =head2 structure
1160  
1161 my $text = structure($ref, output => 'string');
1162 structure(\%config, max_depth => 2, as => 'config');
1163  
1164 Prints the I<shape> of a data structure rather than its values: C<p> shows every element of a 50,000-element array of records, while C<structure> merges them into one and shows the record once.
1165  
1166 my @people = (
1167 { name => 'Ann', age => 31, langs => ['perl', 'R'] },
1168 { name => 'Bo', age => 28, langs => [], email => undef },
1169 );
1170 st @people;
1171  
1172 prints
1173  
1174 ARRAY[2]
1175 [*]: HASH{4} (from 2 instances)
1176 age: number
1177 email?: null
1178 langs: ARRAY[0-2] (from 2 instances)
1179 [*]: string
1180 name: string
1181  
1182 A key that only some of the merged hashes have is marked C<?>. Values in the same place that are of different kinds are shown as a C<UNION> of each kind. Arrays show the range of their lengths. Blessed references show their class. A reference to something already being described further out is not followed again. It is shown as C<(cycle)> when it leads back to the container that holds it, so that following it would go round forever, and as C<(shown above)> when it does not, as when the same hash is both an element of an array and held by another element; a place holding both kinds shows C<(cycle)|(shown above)>.
1183  
1184 It takes these options after the reference:
1185  
1186 =over
1187  
1188 =item * C<output> (default C<stdout>): C<stdout> or C<stderr> to print there; C<string> to print nothing. The text is returned in every case.
1189  
1190 =item * C<color> (default C<auto>): C<1> or C<0>. C<auto> colours the output when it goes to a terminal, or when C<CLICOLOR_FORCE> is set, unless C<NO_COLOR> is set.
1191  
1192 =item * C<max_depth> (default C<0>): How many levels to descend before printing C<(...)>; C<0> is no limit.
1193  
1194 =item * C<hash_max> (default C<32>): A hash with more keys than this is taken to be a lookup table, and its values are merged into one entry, C<< E<lt>*E<gt> >>, rather than listed by key. C<0> lists every key.
1195  
1196 =item * C<as> (no default): A line to print above the structure.
1197  
1198 =back
1199  
1200 =head2 st
1201  
1202 st %hash;
1203 st @array;
1204 st $ref, max_depth => 2;
1205  
1206 C<structure>, called the way C<p> is called: the argument is a variable, not a reference to one, and the options follow it. As with C<p>, it must be a variable -- C<st(\%h)> and C<st(func())> do not compile; call C<structure> for those.
1207  
1208 =head1 Installation
1209  
1210 cpanm Cn::Util
1211  
1212 or, from a copy of the repository:
1213  
1214 perl Makefile.PL
1215 make
1216 make test
1217 make install
1218  
1219 =head1 Compatibility
1220  
1221 C<Cn::Util> runs on perl 5.10.1 and later, and is tested there. C<execute> hands its command to the shell, so the command has to be written for the shell of the system it runs on. On Windows, the paths C<dir> returns are joined with C</>, which perl accepts there, and a C<\> in the C<dir> argument is returned as C</>, so C<< dir =E<gt> q{C:\Temp} >> lists C<C:/Temp/a.txt>; recursive listings with C<cpu> rely on C<Parallel::ForkManager>'s emulated C<fork>.
1222  
1223 =head1 Author
1224  
1225 David E. Condon L<mailto:dec986@gmail.com>
1226  
1227 =head1 License
1228  
1229 This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
1230  
1231 =head1 Thanks
1232  
1233 A lot of this work used Claude AI, which was paid for by the University of Idaho's IMCI
↑ Summary