blib/lib/Util/Cn.pm

filter: Statementstmt 91.6% 352 / 384 Branchbran 72.6% 151 / 208 Conditioncond 50.0% 50 / 100 MC/DCmcdc 34.5% 19 / 55 Subroutinesub 100% 36 / 36 Podpod 100% 10 / 10 totaltotal 77.9% 618 / 793 CC 155 SCAR 29.1
CC
155
Cov
80%
_structure_kind
69.1
_structure_describe
27.7
_structure_render
23.9
CRAP 18.4
↑ Summary
1 # ABSTRACT: Small everyday helpers: directory listing, shell commands, JSON files, number formatting, and data-structure shapes
2 86 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 86 ▶use feature 'say';
Subroutine BEGIN: called CC=1 SCAR=0.0
4 86 ▶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 Util::Cn` has always given the caller
8 # this, so it stays at the top, where loading the module is enough.
9 86 ▶use Devel::Confess;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 package Util::Cn;
12 86 require 5.010001;
13 86 our $VERSION = 0.021;
14 86 require Exporter;
15 86 our @ISA = ('Exporter');
16 86 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 Util::Cn`. 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 Util::Cn` 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 Util/Cn.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 Util::Cn` 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 Util::Cn ();` skips import() entirely, per normal Perl semantics,
71 # so that is the escape hatch for a caller that wants none of this.
72 # ---------------------------------------------------------------------------
73 87 ▶sub import {
Subroutine import: called CC=2 SCAR=7.0
74 87 my $class = shift;
75 87 $class->export_to_level(1, $class, @_); # the @EXPORT subs, one level up
76  
77 87 my ($pkg, $file, $line) = caller;
78 87 _install_ddp_stubs($pkg);
79 87 require autodie;
80 87 ▶ 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 "Util::Cn: could not propagate autodie to ${file}: $@" 87 0 87
81 or die "Util::Cn: could not propagate autodie to $file: $@";
82 87 $autodie->();
83 87 return;
84 }
85  
86 # Scripts rely on `use Util::Cn` 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 # Util::Cn, 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 86 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 87 ▶sub _install_ddp_stubs {
Subroutine _install_ddp_stubs: called CC=3 SCAR=11.0
102 87 my ($pkg) = @_;
103 86 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
104 87 for my $name ('p', 'np') {
105 174 my $glob = "${pkg}::$name";
106 174 ▶ next if defined &{$glob};
Branch: 1 branch
BranchTrueFalseTotal
if defined &{$glob;} 1 173 174
107 173 ▶ *{$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 "Util::Cn: 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 173 };
116 }
117 87 return;
118 }
119  
120 4 ▶sub _load_ddp {
Subroutine _load_ddp: called CC=7 SCAR=19.8
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 86 ▶ 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 2 my $ok = eval qq{package $pkg;\nDDP->import({output => 'STDOUT', array_max => 10, show_memsize => 1, show_dualvar => 'off'}); 1};
143 2 ▶ die "Util::Cn: could not load DDP into $pkg: $@" unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 2 2
144 2 $DDP_LOADED{$pkg} = 1;
145 2 return;
146 }
147  
148 1371 ▶sub dir {
Subroutine dir: called CC=19 SCAR=29.5
Pod documented
149 1371 my %args = (
150 tests => 'f',
151 dir => '.',
152 regex => '.',
153 recursive => 0,
154 on_match => undef, # optional callback: streams results, keeps RAM flat
155 cpu => 1, # worker processes for a recursive walk; 1 = no forking
156 @_,
157 );
158  
159 1371 my %allowed = map { $_ => 1 } qw(tests dir regex recursive on_match cpu);
160 1371 ▶ if (my @bad = grep { !$allowed{$_} } keys %args) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@bad) = grep({not $allowed{$_};} keys %args)) 1 1370 1371
161 1 die "Unrecognized arguments: @bad\nAccepted args: "
162 . join(', ', sort keys %allowed);
163 }
164 # Added 's' (non-zero size), removed 't' (tty test - meaningless on a path)
165 die "Unrecognized characters in tests: $args{tests}"
166 1370 ▶ if $args{tests} =~ /[^rwxoRWXOezsfdlpSbcugkTB]/;
Branch: 1 branch
BranchTrueFalseTotal
if $args{"tests"} =~ /[^rwxoRWXOezsfdlpSbcugkTB]/ 1 1369 1370
167 die "cpu must be a positive integer, got '$args{cpu}'"
168 1369 ▶ unless $args{cpu} =~ /\A[1-9][0-9]*\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"cpu"} =~ /\A[1-9][0-9]*\z/ 2 1367 1369
169 1367 ▶ my $re = eval { qr/$args{regex}/ }
Branch: 1 branch
BranchTrueFalseTotal
my $re = eval { do { qr/$args{"regex"}/ } } or die qq[Invalid regex '$args{"regex"}': $@] 1366 1 1367
170 or die "Invalid regex '$args{regex}': $@";
171 # Compile the tests once. The first test stats the path; every later test
172 # reuses the stat buffer via the special '_' filehandle, so N tests cost
173 # one stat(2) syscall instead of N (~2.4x faster for 4 tests).
174 # -l needs lstat, so it is hoisted to the front, and the test after it
175 # must re-stat the real path (otherwise '_' holds lstat data, or -l _
176 # would be a fatal error).
177 1366 my @t = split //, $args{tests};
178 1366 @t = ((grep { $_ eq 'l' } @t), (grep { $_ ne 'l' } @t));
179 1366 my @parts;
180 1366 my $fresh = 1; # 1 = the next test must stat the path itself rather than reuse '_'
181 1366 for my $t (@t) {
182 0 ▶ if ($t eq 'l') { push @parts, '-l $_[0]'; $fresh = 1 }
Branch: 2 branches
BranchTrueFalseTotal
if ($t eq 'l') { } 0 1146 1146
elsif ($fresh) { } 1146 0 1146
183 1146 elsif ($fresh) { push @parts, "-$t \$_[0]"; $fresh = 0 }
184 0 else { push @parts, "-$t _" }
185 }
186 my $tester = @parts
187 ? (eval 'sub { ' . join(' && ', @parts) . ' }'
188 or die "Failed to compile tests: $@")
189 1366 ▶ : 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 ? : 1146 220 1366
Condition50%1/2
eval 'sub { ' . join(" && ", @parts) . ' }' or die "Failed to compile tests: $@"
l!l
11460
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
190  
191 1366 my $target_dir = $args{dir};
192 # Strip trailing slashes, but keep "/" intact. (?<=.) rather than
193 # (?<=[^/]), which left "///" as it was, to be joined as "////etc".
194 1366 $target_dir =~ s{(?<=.)/+\z}{}s;
195 # "." is left off the front of results; "/" must not become "//etc".
196 9950 ▶ my $join = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
197 9950 my ($d, $item) = @_;
198 9950 ▶ $d eq '.' ? $item : $d eq '/' ? "/$item" : "$d/$item"
Branch: 2 branches
BranchTrueFalseTotal
$d eq '.' ? : 117 9833 9950
$d eq '/' ? : 3234 6599 9833
199 1366 };
200  
201 1366 my $cb = $args{on_match};
202 1366 my @items;
203 1366 ▶ 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
9812680
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
204  
205 1366 ▶ if ($args{recursive}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'recursive'}) { } 797 569 1366
206 797 require File::Find; # ~1.6 ms, and only the recursive branch needs it
207 # Walk everything strictly below $start, handing each match to $sink.
208 504 ▶ my $find = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
209 504 my ($start, $sink) = @_;
210 504 my $strip = $start eq '.';
211 # File::Find lstat()s its starting path, so a $start that is a
212 # symlink to a directory was taken for a file and nothing was
213 # found under it -- although opendir, which the non-recursive
214 # listing and the parallel walk's top levels use, follows it. A
215 # trailing slash makes lstat resolve the link; File::Find strips
216 # the slash again only after the lstat (1.14 in perl 5.10.1 and
217 # 1.44 in 5.44 alike), so the paths it reports are unchanged.
218 File::Find::find({
219 no_chdir => 1,
220 20934 ▶ wanted => sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
221 20934 ▶ return if $_ eq $start; # $start itself is not "below" it
Branch: 1 branch
BranchTrueFalseTotal
if $_ eq $start 504 20430 20934
222 20430 my ($file) = m{([^/]+)\z}s; # basename, much cheaper than File::Spec
223 20430 ▶ if ($file =~ $re && $tester->($_)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($file =~ /$re/ and &$tester($_)) 11849 8581 20430
Condition100%3/3
$file =~ /$re/ and &$tester($_)
!ll&&!rl&&r
2613596811849
MC/DC100%2/2
$file =~ /$re/ and &$tester($_)
$file =~ /$re/ &$tester($_)
Truth table100%3/3
A and B
A= $file =~ /$re/B= &$tester($_)
ABresult
0X0
100
111
224 11849 my $path = $_;
225 11849 ▶ $path =~ s{^\./}{} if $strip;
Branch: 1 branch
BranchTrueFalseTotal
if $strip 324 11525 11849
226 11849 $sink->($path);
227 }
228 },
229 504 ▶ }, -l $start ? "$start/" : $start);
Branch: 1 branch
BranchTrueFalseTotal
-l $start ? : 50 454 504
230 797 };
231 797 ▶ if ($args{cpu} == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'cpu'} == 1) { } 396 401 797
232 396 $find->($target_dir, $emit);
233 } else {
234 401 _dir_parallel($target_dir, $args{cpu}, $re, $tester, $join, $find, $emit);
235 }
236 } else {
237 # cpu is ignored here on purpose: one readdir plus one stat per entry
238 # is ~6 us warm, far below the cost of forking and shipping results back.
239 569 ▶ opendir my $dh, $target_dir
Branch: 1 branch
BranchTrueFalseTotal
opendir my $dh, $target_dir or die "Cannot open directory ${target_dir}: $!" 568 1 569
240 or die "Cannot open directory $target_dir: $!";
241 568 ▶ while (defined(my $item = readdir $dh)) { # defined(): a file named "0" is falsy
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $item = readdir $dh)) 6672 568 7240
242 6672 ▶ next if $item =~ /\A\.\.?\z/; # \A..\z: "$" would match before a trailing \n
Branch: 1 branch
BranchTrueFalseTotal
if $item =~ /\A\.\.?\z/ 1136 5536 6672
243 5536 ▶ next if $item !~ $re;
Branch: 1 branch
BranchTrueFalseTotal
unless $item =~ /$re/ 799 4737 5536
244 4737 my $path = $join->($target_dir, $item);
245 4737 ▶ $emit->($path) if $tester->($path);
Branch: 1 branch
BranchTrueFalseTotal
if &$tester($path) 4198 539 4737
246 }
247 568 closedir $dh;
248 }
249 1289 ▶ return $cb ? () : @items;
Branch: 1 branch
BranchTrueFalseTotal
$cb ? : 86 1203 1289
250 }
251  
252 # Jobs handed out per worker. Parallel::ForkManager starts a new job whenever
253 # a worker finishes, so more jobs than workers is what evens out a tree whose
254 # subdirectories differ wildly in size; each job costs one fork plus one
255 # Storable round-trip through a temp file, so too many jobs loses again.
256 # Measured 2026-09-23, 20-core NVMe box, warm cache, best of 3, seconds:
257 #
258 # tree (files) serial k=1 k=2 k=4 k=8 k=16
259 # ~/perl5 (150k), cpu=8 1.23 0.95 0.25 0.29 0.36 0.47
260 # ~/perl5 (150k), cpu=4 1.23 1.03 0.82 0.39 0.45 0.61
261 # perlbrew/build (120k), cpu=8 0.75 0.19 0.24 0.25 0.33 0.44
262 #
263 # k=1 and k=2 collapse on the skewed tree; 4 is the smallest value that does
264 # not. Re-run: edit the value below, then time
265 # perl -Ilib -MUtil::Cn -e 'dir(dir => $ARGV[0], recursive => 1, cpu => 8)' TREE
266 86 my $DIR_JOBS_PER_CPU = 4;
267  
268 # Recursive dir() across $cpu worker processes. Results come back to this
269 # process and go through $emit here, so an on_match closure still sees and
270 # mutates the caller's variables -- it just runs after a whole job's batch
271 # arrives rather than per file, and match order differs from the serial walk.
272 401 ▶sub _dir_parallel {
Subroutine _dir_parallel: called CC=18 SCAR=29.8
273 401 my ($root, $cpu, $re, $tester, $join, $find, $emit) = @_;
274 401 require Parallel::ForkManager; # not core, and only cpu > 1 needs it
275  
276 # One subtree per job would starve the pool whenever a single directory
277 # holds most of the tree (~/perl5: one of 3 top-level dirs has 99% of the
278 # files, and a top-level split gave no speedup at any cpu). So walk
279 # breadth-first here until a level is wide enough to share out, testing
280 # the entries of every level walked; the final level's directories are
281 # already tested and become the jobs.
282 401 my $want = $cpu * $DIR_JOBS_PER_CPU;
283 401 my @level = ($root);
284 401 ▶ while (@level && @level < $want) {
Branch: 1 branch
BranchTrueFalseTotal
if (@level and @level < $want) 401 401 802
Condition66%2/3
@level and @level < $want
!ll&&!rl&&r
0401401
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
285 401 my @next;
286 401 for my $d (@level) {
287 401 ▶ opendir my $dh, $d or die "Cannot open directory $d: $!";
Branch: 1 branch
BranchTrueFalseTotal
opendir my $dh, $d or die "Cannot open directory ${d}: $!" 401 0 401
288 401 ▶ while (defined(my $item = readdir $dh)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $item = readdir $dh)) 6015 401 6416
289 6015 ▶ next if $item =~ /\A\.\.?\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $item =~ /\A\.\.?\z/ 802 5213 6015
290 5213 my $path = $join->($d, $item);
291 5213 ▶ $emit->($path) if $item =~ $re && $tester->($path);
Branch: 1 branch
BranchTrueFalseTotal
if $item =~ /$re/ and &$tester($path) 2067 3146 5213
Condition100%3/3
$item =~ /$re/ and &$tester($path)
!ll&&!rl&&r
137817682067
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
292 5213 ▶ push @next, $path if !-l $path && -d _; # lstat: File::Find does not follow symlinks either
Branch: 1 branch
BranchTrueFalseTotal
if not -l $path and -d _ 4812 401 5213
Condition66%2/3
not -l $path and -d _
!ll&&!rl&&r
40104812
MC/DC50%1/2
not -l $path and -d _
not -l $path -d _
Truth table66%2/3
not(A) and B
A= not -l $pathB= -d _
ABresult
0X0
100
111
293 }
294 401 closedir $dh;
295 }
296 401 @level = @next;
297 }
298 401 ▶ return unless @level;
Branch: 1 branch
BranchTrueFalseTotal
unless @level 0 401 401
299  
300 401 my @jobs;
301 401 push @{ $jobs[$_ % $want] }, $level[$_] for 0 .. $#level;
302  
303 401 my @errors;
304 401 my $pm = Parallel::ForkManager->new($cpu);
305 # The default 1 s poll in wait_all_children added a flat 1.01 s to every
306 # call, measured; 0 makes it block in waitpid instead.
307 401 $pm->set_waitpid_blocking_sleep(0);
308 2849 ▶ $pm->run_on_finish(sub {
Subroutine __ANON__: called CC=6 SCAR=22.8
309 2849 my ($pid, $exit, $id, $signal, $core, $data) = @_;
310 2849 ▶ if ($signal || $exit || !$data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($signal or $exit or not $data) 0 2849 2849
Condition33%2/6
$signal or $exit or not $data
l!l&&r!l&&!r
002849
$signal or $exit
l!l&&r!l&&!r
002849
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
311 0 push @errors, "dir: worker $pid died (exit $exit, signal $signal)";
312 0 return;
313 }
314 2849 ▶ push @errors, $data->{error} if defined $data->{error};
Branch: 1 branch
BranchTrueFalseTotal
if defined $data->{"error"} 0 2849 2849
315 2849 $emit->($_) for @{ $data->{paths} };
316 401 });
317 401 for my $job (@jobs) {
318 3002 ▶ $pm->start and next;
Branch: 1 branch
BranchTrueFalseTotal
$pm->start and next 2926 76 3002
319 76 my @found;
320 76 ▶ my $ok = eval { $find->($_, sub { push @found, $_[0] }) for @$job; 1 };
Subroutine __ANON__: called CC=1 SCAR=0.0
321 76 ▶ $pm->finish(0, { paths => \@found, error => $ok ? undef : "$@" });
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 76 0 76
322 }
323 325 $pm->wait_all_children;
324 325 ▶ die join "\n", @errors if @errors;
Branch: 1 branch
BranchTrueFalseTotal
if @errors 0 325 325
325 325 return;
326 }
327  
328 8 ▶sub execute {
Subroutine execute: called CC=15 SCAR=27.8
Pod documented
329 8 my ($cmd, $return, $die) = @_;
330 8 ▶ $return = 'exit' unless defined $return;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $return 2 6 8
331 8 ▶ $die = 1 unless defined $die;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $die 7 1 8
332 8 ▶ if ($return !~ m/^(exit|stdout|stderr|all)$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($return =~ /^(exit|stdout|stderr|all)$/) 1 7 8
333 1 die "you gave \$return = \"$return\", while this subroutine only accepts ^(exit|stdout|stderr|all)\$";
334 }
335 7 require Capture::Tiny; # ~7.5 ms
336 # Capture::Tiny redirects fd 1 and fd 2 and nothing else, so the child still
337 # inherits the parent's fd 0. A child that prompts -- rm on a
338 # write-protected file, cp -i, apt -- prompts only when fd 0 is a tty, then
339 # writes its question into the captured stderr where nobody can see it and
340 # blocks on the terminal for an answer the user does not know is wanted.
341 # (Observed 2026-09-13: `rm -r` on read-only cl.tex hung jobsearch/tex/tar.pl
342 # indefinitely.) Pointing fd 0 at /dev/null turns the prompt into an instant
343 # EOF, so such a child declines and exits instead of hanging.
344 # Reopening STDIN is the point, not `local *STDIN`: the child inherits the
345 # descriptor, and only reopening the handle perl holds on fd 0 -- which frees
346 # fd 0 and so reclaims it as the lowest available -- puts /dev/null there.
347 7 require File::Spec;
348 7 my $saved_stdin;
349 7 ▶ open $saved_stdin, '<&', \*STDIN or die "cannot save STDIN: $!"
Branch: 1 branch
BranchTrueFalseTotal
if defined fileno STDIN 7 0 7
Condition40%2/5
defined fileno STDIN && (open($saved_stdin, '<&', \*STDIN) || die("cannot save STDIN: $!"))
!ll&&!rl&&r
070
open $saved_stdin, "<&", \*STDIN or die "cannot save STDIN: $!"
l!l
70
MC/DC0%0/2
defined fileno STDIN && (open($saved_stdin, '<&', \*STDIN) || die("cannot save STDIN: $!"))
defined fileno STDIN open $saved_stdin, "<&", \*STDIN
Truth table0%0/3
A && B
A= defined fileno STDINB= open $saved_stdin, "<&", \*STDIN
ABresult
0X0
100
111
350 if defined fileno STDIN; # a caller may legitimately have closed it
351 7 ▶ open STDIN, '<', File::Spec->devnull or die "cannot reopen STDIN on devnull: $!";
Branch: 1 branch
BranchTrueFalseTotal
open STDIN, "<", "File::Spec"->devnull or die "cannot reopen STDIN on devnull: $!" 7 0 7
352 # An explicit sub{} rather than capture { ... }: the prototype that makes
353 # the block form legal is not visible at compile time under a runtime
354 # require, so perl would try to parse the block as an anonymous hash.
355 7 ▶ my ($stdout, $stderr, $exit) = Capture::Tiny::capture(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
356 7 system( $cmd )
357 7 });
358 7 ▶ if (defined $saved_stdin) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $saved_stdin) { } 7 0 7
359 7 ▶ open STDIN, '<&', $saved_stdin or die "cannot restore STDIN: $!";
Branch: 1 branch
BranchTrueFalseTotal
open STDIN, "<&", $saved_stdin or die "cannot restore STDIN: $!" 7 0 7
360 } else {
361 0 close STDIN;
362 }
363 7 ▶ if (($die == 1) && ($exit != 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($die == 1 and $exit != 0) 1 6 7
Condition100%3/3
$die == 1 and $exit != 0
!ll&&!rl&&r
151
MC/DC100%2/2
$die == 1 and $exit != 0
$die == 1 $exit != 0
Truth table100%3/3
A and B
A= $die == 1B= $exit != 0
ABresult
0X0
100
111
364 1 say STDERR "exit = $exit";
365 1 say STDERR "STDOUT = $stdout";
366 1 say STDERR "STDERR = $stderr";
367 1 die "$cmd\n failed";
368 }
369 6 ▶ if ($return eq 'exit') {
Branch: 4 branches
BranchTrueFalseTotal
if ($return eq 'exit') { } 2 4 6
elsif ($return eq 'stderr') { } 1 3 4
elsif ($return eq 'stdout') { } 2 1 3
elsif ($return eq 'all') { } 1 0 1
370 2 return $exit
371 } elsif ($return eq 'stderr') {
372 1 chomp $stderr;
373 1 return $stderr
374 } elsif ($return eq 'stdout') {
375 2 chomp $stdout;
376 2 return $stdout
377 } elsif ($return eq 'all') {
378 1 chomp $stdout;
379 1 chomp $stderr;
380 return {
381 1 exit => $exit,
382 stdout => $stdout,
383 stderr => $stderr
384 }
385 } else {
386 0 die "$return broke pigeonholes"
387 }
388 0 return $stdout
389 }
390  
391 3 ▶sub file2string {
Subroutine file2string: called CC=2 SCAR=6.9
Pod documented
392 3 my ($file) = @_;
393 3 ▶ open my $fh, '<', $file or die "can't read $file: $!"; # was autodie
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $file or die "can't read ${file}: $!" 2 1 3
394 2 return do { local $/; <$fh> };
395 }
396  
397 28 ▶sub format_commas { # https://stackoverflow.com/questions/33442240/perl-printf-to-use-commas-as-thousands-separator
Subroutine format_commas: called CC=8 SCAR=20.8
Pod documented
398 28 my ($n, $format) = @_;
399 28 ▶ $format = '.%02d' unless defined $format;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $format 17 11 28
400 # '%.0u' is the documented way to ask for a whole number, but sprintf
401 # prints nothing for it only when the hundredths are 0: 1234.56 came out
402 # "1,23456". So '%.0u' is recognised here, rounds half up to a whole
403 # number, and prints no fraction at all.
404 28 my $whole = $format eq '%.0u';
405 28 my $neg = $n < 0;
406 28 my $abs = abs $n;
407 28 my ($int, $cents);
408 28 ▶ if ($whole) {
Branch: 1 branch
BranchTrueFalseTotal
if ($whole) { } 11 17 28
409 11 $int = int($abs + .5);
410 11 $cents = 0;
411 } else {
412 17 $int = int $abs;
413 # int(100 * (.005 + frac)) is the original expression, and is exactly
414 # round-half-up to hundredths -- .005 * 100 is the +0.5 before truncation.
415 # It is kept verbatim so no already-correct result shifts by a cent.
416 17 $cents = int(100 * (.005 + ($abs - $int)));
417 # ...but it can land on 100 (.999 rounds up to 1.00), which used to be
418 # printed straight into the fraction: 999999.999 came out "999,999.100".
419 # The carry has to go into the integer part instead.
420 17 ▶ if ($cents >= 100) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cents >= 100) 5 12 17
421 5 $int++;
422 5 $cents -= 100;
423 }
424 }
425 # Split off the sign and work on the magnitude: the old code fed a negative
426 # through int()/sprintf and produced "-1,234.-49" for -1234.5, and lost the
427 # sign entirely for -0.5. A value that rounds to zero stays unsigned, so
428 # -0.001 is "0.00" rather than "-0.00".
429 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
430 # '%.0f' rather than interpolating $int: a large magnitude stringifies in
431 # scientific notation, and the reverse/unpack grouping shredded that into
432 # "1e,+20" for 1e20.
433 28 my $digits = sprintf '%.0f', $int;
434 28 ▶ return $sign . reverse(join(',', unpack('(A3)*', reverse $digits))) . ($whole ? '' : sprintf($format, $cents));
Branch: 1 branch
BranchTrueFalseTotal
$whole ? : 11 17 28
435 }
436  
437 5 ▶sub json_file_to_ref {
Subroutine json_file_to_ref: called CC=4 SCAR=13.9
Pod documented
438 5 my ($json_filename) = @_;
439 5 ▶ die "$json_filename doesn't exist or isn't a file" unless -f $json_filename;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $json_filename 1 4 5
440 4 ▶ die "$json_filename has 0 size" if -s $json_filename == 0;
Branch: 1 branch
BranchTrueFalseTotal
if -s $json_filename == 0 1 3 4
441 3 ▶ 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}: $!" 3 0 3
442 3 my $json = do { local $/; <$fh> }; # slurp; $/ restored immediately
443 3 close $fh;
444 # Python/NumPy emit bare NaN / Infinity / -Infinity, which are not valid
445 # JSON. Rewrite them to null (-> undef) only when they sit in JSON value
446 # position (after '[', ',' or ':'). That test alone also matched text
447 # inside a string -- "values: [1, NaN, 2]" became "values: [1, null, 2]"
448 # -- so the first alternative matches each whole string literal and
449 # (*SKIP)(*FAIL) resumes the scan after its closing quote.
450 3 $json =~ s/"(?:[^"\\]++|\\.)*+"(*SKIP)(*FAIL)|[\[,:]\s*\K-?(?:NaN|Infinity)(?=\s*[,\]}])/null/gs;
451 3 require JSON::MaybeXS; # ~4.3 ms
452 3 return JSON::MaybeXS::decode_json($json);
453 }
454  
455 # These return *some* key/value from the hash, not a random one -- whichever
456 # pair the hash's internal iterator yields first.
457 #
458 # They used to be `foreach my $key (keys %{$hash}) { return $key }`, which is
459 # O(n): `keys` in list context materializes EVERY key into a temporary list,
460 # and then the loop throws all but the first away. On a 50,000-key hash that
461 # was 1.48 ms per call; via each() it is 0.15 us, ~10,000x faster.
462 #
463 # The bare `keys` in void context resets the iterator, so repeated calls keep
464 # returning the first pair instead of walking off the end of the hash. It is
465 # reset again after the each(), which would otherwise leave it one pair in, so
466 # that a caller's own `while (each %h)` afterwards skipped the first pair.
467 # The old `keys`-in-list-context version left it at the start, and so do these.
468 #
469 # Falling off a foreach also returned '' rather than undef in scalar context;
470 # each() on an empty hash returns an empty list, so these now yield a true
471 # undef, which is what t/random.t always asserted.
472 4 ▶sub random_key {
Subroutine random_key: called CC=1 SCAR=0.0
Pod documented
473 4 my ($hash) = @_;
474 4 keys %{ $hash }; # reset the iterator
475 4 my ($key) = each %{ $hash };
476 4 keys %{ $hash };
477 4 return $key;
478 }
479  
480 4 ▶sub random_value {
Subroutine random_value: called CC=1 SCAR=0.0
Pod documented
481 4 my ($hash) = @_;
482 4 keys %{ $hash }; # reset the iterator
483 4 my (undef, $value) = each %{ $hash };
484 4 keys %{ $hash };
485 4 return $value;
486 }
487  
488 2 ▶sub ref_to_json_file {
Subroutine ref_to_json_file: called CC=3 SCAR=11.0
Pod documented
489 2 my ($ref, $json_filename) = @_;
490 2 my $ref_json_filename = ref $json_filename;
491 2 ▶ unless ($ref_json_filename eq '') {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ref_json_filename eq "") 1 1 2
492 1 die "$json_filename isn't a scalar/string";
493 }
494 1 require JSON::MaybeXS;
495 1 require Term::ANSIColor;
496 1 ▶ 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}: $!" 1 0 1
497 or die "can't write $json_filename: $!"; # was autodie
498 1 say $fh JSON::MaybeXS::encode_json($ref);
499 1 say 'Wrote ' . Term::ANSIColor::colored(['blue on_red'], $json_filename);
500 1 return $json_filename;
501 }
502  
503 # ----------------------------------------------------------------------------
504 # structure(): print the *shape* of a data structure instead of its values.
505 #
506 # p() from Data::Printer shows you every value; when a 50,000-element array
507 # holds the same kind of record over and over, that is the wrong tool. This
508 # merges all elements of an array into ONE representative node, so you see the
509 # schema once. Keys absent from some of the merged records are flagged '?';
510 # values that disagree about their type become a UNION.
511 #
512 # Two entry points, mirroring DDP's own p()/np() split:
513 # st() - prototyped, so `st %hash` works like `p %hash`. Use this
514 # interactively.
515 # structure() - plain sub, takes a reference: structure(\%hash), or the
516 # return value of another call. Use this from other code.
517 #
518 # Scalar::Util and Term::ANSIColor are require'd in structure(), which st()
519 # also funnels through, so the per-value helpers below can call them fully
520 # qualified without re-checking %INC on every node. Scalar::Util is not loaded
521 # at `use` time because it drags in List::Util's XS bootstrap (~4 ms) and only
522 # this family ever touches it.
523  
524 86 my %STRUCTURE_COLOR = (
525 key => 'bold', # hash key names
526 opt => 'red', # the '?' optional marker
527 HASH => 'bold cyan',
528 ARRAY => 'bold yellow',
529 UNION => 'bold magenta',
530 elem => 'bright_black', # the '[*]' / '<alt>' / '(empty)' markers
531 class => 'bold white', # blessed package names
532 number => 'green',
533 string => 'bright_blue',
534 bool => 'bright_magenta',
535 null => 'bright_black',
536 CODE => 'yellow',
537 other => 'red', # anything unexpected
538 );
539  
540 43 ▶sub _structure_color {
Subroutine _structure_color: called CC=3 SCAR=16.5
541 43 my ($name, $text, $use_color) = @_;
542 43 ▶ return $text unless $use_color;
Branch: 1 branch
BranchTrueFalseTotal
unless $use_color 43 0 43
543 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
544 }
545  
546 # Classify one value. Blessed containers keep their package name so that
547 # Foo=HASH and a plain HASH don't get merged into the same node.
548 25 ▶sub _structure_kind {
Subroutine _structure_kind: called CC=13 SCAR=42.4
549 25 my ($v) = @_;
550 25 ▶ return 'null' unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 25 25
551 25 my $r = ref $v;
552 25 ▶ return (Scalar::Util::looks_like_number($v) ? 'number' : 'string') if $r eq '';
Branch: 2 branches
BranchTrueFalseTotal
if $r eq "" 10 15 25
&Scalar::Util::looks_like_number($v) ? : 8 2 10
553 15 ▶ if (my $class = Scalar::Util::blessed($v)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $class = builtin::blessed($v)) 0 15 15
554 0 ▶ 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 0 0
Condition0%0/3
$class eq "JSON::PP::Boolean" or $class eq "Types::Serialiser::Boolean"
l!l&&r!l&&!r
000
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 table0%0/3
A or B
A= $class eq "JSON::PP::Boolean"B= $class eq "Types::Serialiser::Boolean"
ABresult
1X1
011
000
555 0 ▶ return 'Regexp' if $class eq 'Regexp';
Branch: 1 branch
BranchTrueFalseTotal
if $class eq "Regexp" 0 0 0
556 0 ▶ my $rt = Scalar::Util::reftype($v) // '';
Condition0%0/2
builtin::reftype($v) // ""
l!l
00
MC/DC0%0/1
builtin::reftype($v) // ""
builtin::reftype($v)
Truth table0%0/2
A
A= builtin::reftype($v)
Aresult
11
00
557 0 ▶ 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" 0 0 0
Condition0%0/9
$rt eq "HASH" or $rt eq "ARRAY" or $rt eq "SCALAR" or $rt eq "REF"
l!l&&r!l&&!r
000
$rt eq "HASH" or $rt eq "ARRAY" or $rt eq "SCALAR"
l!l&&r!l&&!r
000
$rt eq "HASH" or $rt eq "ARRAY"
l!l&&r!l&&!r
000
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 table0%0/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
558 0 return $class;
559 }
560 15 return $r; # HASH ARRAY SCALAR REF CODE GLOB
561 }
562  
563 # Merge a list of same-position values into a single structural node:
564 # { kind => 'hash', keys => { k => { node => .., optional => 0|1 } }, n, class }
565 # { kind => 'array', node => .., n => #instances, lens => [lengths], class }
566 # { kind => 'sref', node => .. } # \$x and \\$x
567 # { kind => 'leaf', types => { typename => 1, ... } }
568 # { kind => 'union', alts => { kindname => node } }
569 # $stack holds the refaddrs of the containers we are currently inside, so a
570 # self-referential structure terminates instead of recursing forever.
571 23 ▶sub _structure_describe {
Subroutine _structure_describe: called CC=22 SCAR=33.2
572 23 my ($values, $opt, $depth, $stack) = @_;
573 23 my %by_kind;
574 23 push @{ $by_kind{ _structure_kind($_) } }, $_ for @{ $values };
575 23 my @kinds = sort keys %by_kind;
576  
577 23 ▶ if (@kinds > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@kinds > 1) 0 23 23
578 return {
579 kind => 'union',
580 0 alts => { map { $_ => _structure_describe($by_kind{$_}, $opt, $depth, $stack) } @kinds },
581 };
582 }
583 23 ▶ my $k = $kinds[0] // 'null';
Condition50%1/2
$kinds[0] // "null"
l!l
230
MC/DC0%0/1
$kinds[0] // "null"
$kinds[0]
Truth table50%1/2
A
A= $kinds[0]
Aresult
11
00
584 23 my ($class, $reftype) = $k =~ /\A(.+)=(HASH|ARRAY|SCALAR|REF)\z/;
585 23 ▶ $reftype //= $k;
Condition33%1/3
$reftype //= $k
l!l&&r!l&&!r
0230
MC/DC0%0/2
$reftype //= $k
$reftype $k
Truth table33%1/3
A //= B
A= $reftypeB= $k
ABresult
1X1
011
000
586  
587 23 ▶ 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") 15 8 23
Condition100%9/9
$reftype eq "HASH" or $reftype eq "ARRAY" or $reftype eq "SCALAR" or $reftype eq "REF"
l!l&&r!l&&!r
1148
$reftype eq "HASH" or $reftype eq "ARRAY" or $reftype eq "SCALAR"
l!l&&r!l&&!r
10112
$reftype eq "HASH" or $reftype eq "ARRAY"
l!l&&r!l&&!r
7313
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
588 # Drop anything we're already inside: its shape is an ancestor's shape.
589 15 my @fresh = grep { !$stack->{ Scalar::Util::refaddr($_) } } @{ $values };
590 15 ▶ return { kind => 'leaf', types => { '(cycle)' => 1 } } unless @fresh;
Branch: 1 branch
BranchTrueFalseTotal
unless @fresh 0 15 15
591 15 ▶ if ($opt->{max_depth} && $depth >= $opt->{max_depth}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"max_depth"} and $depth >= $opt->{"max_depth"}) 0 15 15
Condition33%1/3
$opt->{"max_depth"} and $depth >= $opt->{"max_depth"}
!ll&&!rl&&r
1500
MC/DC0%0/2
$opt->{"max_depth"} and $depth >= $opt->{"max_depth"}
$opt->{"max_depth"} $depth >= $opt->{"max_depth"}
Truth table33%1/3
A and B
A= $opt->{"max_depth"}B= $depth >= $opt->{"max_depth"}
ABresult
0X0
100
111
592 0 return { kind => 'leaf', types => { '(...)' => 1 } };
593 }
594 15 local @{ $stack }{ map { Scalar::Util::refaddr($_) } @fresh } = (1) x @fresh;
595  
596 15 ▶ if ($reftype eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if ($reftype eq 'HASH') { } 7 8 15
elsif ($reftype eq 'ARRAY') { } 3 5 8
597 7 my %keys; # key => { vals => [...], seen => n }
598 7 for my $h (@fresh) {
599 7 for my $key (keys %{ $h }) {
600 9 push @{ $keys{$key}{vals} }, $h->{$key};
601 9 $keys{$key}{seen}++;
602 }
603 }
604 # A wide hash used as a dictionary has no interesting key names:
605 # merge every value into one representative entry instead.
606 7 ▶ if ($opt->{hash_max} && keys %keys > $opt->{hash_max}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"hash_max"} and keys %keys > $opt->{"hash_max"}) 0 7 7
Condition33%1/3
$opt->{"hash_max"} and keys %keys > $opt->{"hash_max"}
!ll&&!rl&&r
070
MC/DC0%0/2
$opt->{"hash_max"} and keys %keys > $opt->{"hash_max"}
$opt->{"hash_max"} keys %keys > $opt->{"hash_max"}
Truth table33%1/3
A and B
A= $opt->{"hash_max"}B= keys %keys > $opt->{"hash_max"}
ABresult
0X0
100
111
607 0 my @all = map { @{ $keys{$_}{vals} } } keys %keys;
608 return {
609 0 kind => 'hash',
610 class => $class,
611 n => scalar @fresh,
612 wide => scalar keys %keys,
613 keys => { '*' => {
614 node => _structure_describe(\@all, $opt, $depth + 1, $stack),
615 optional => 0,
616 }},
617 };
618 }
619 7 my %out;
620 7 for my $key (keys %keys) {
621 $out{$key} = {
622 node => _structure_describe($keys{$key}{vals}, $opt, $depth + 1, $stack),
623 9 ▶ optional => ($keys{$key}{seen} < @fresh ? 1 : 0),
Branch: 1 branch
BranchTrueFalseTotal
$keys{$key}{'seen'} < @fresh ? : 0 9 9
624 };
625 }
626 7 return { kind => 'hash', class => $class, n => scalar @fresh, keys => \%out };
627 }
628 elsif ($reftype eq 'ARRAY') {
629 3 my (@elems, @lens);
630 3 for my $a (@fresh) {
631 3 push @lens, scalar @{ $a };
632 3 push @elems, @{ $a };
633 }
634 return {
635 3 ▶ kind => 'array',
Branch: 1 branch
BranchTrueFalseTotal
@elems ? : 3 0 3
636 class => $class,
637 node => (@elems ? _structure_describe(\@elems, $opt, $depth + 1, $stack) : undef),
638 n => scalar @fresh,
639 lens => \@lens,
640 };
641 }
642 return { # SCALAR / REF
643 kind => 'sref',
644 class => $class,
645 5 node => _structure_describe([map { ${ $_ } } @fresh], $opt, $depth + 1, $stack),
646 };
647 }
648 8 return { kind => 'leaf', types => { $k => 1 } };
649 }
650  
651 3 ▶sub _structure_array_desc {
Subroutine _structure_array_desc: called CC=6 SCAR=18.5
652 3 my ($node, $c) = @_;
653 3 my @lens = @{ $node->{lens} };
654 3 my ($min, $max) = ($lens[0], $lens[0]);
655 3 ▶ for (@lens) { $min = $_ if $_ < $min; $max = $_ if $_ > $max }
Branch: 2 branches
BranchTrueFalseTotal
if $_ < $min 0 3 3
if $_ > $max 0 3 3
656 3 ▶ my $range = $min == $max ? $min : "$min-$max";
Branch: 1 branch
BranchTrueFalseTotal
$min == $max ? : 3 0 3
657 3 my $out = $c->('ARRAY', "ARRAY[$range]");
658 3 ▶ $out .= " (from $node->{n} instances)" if $node->{n} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $node->{"n"} > 1 0 3 3
659 3 return $out;
660 }
661  
662 23 ▶sub _structure_render {
Subroutine _structure_render: called CC=17 SCAR=31.7
663 23 my ($label, $node, $indent, $opt, $c, $lines) = @_;
664 23 ▶ my $pad = (' ' x $indent) . ($label // '');
Condition100%2/2
$label // ""
l!l
176
MC/DC100%1/1
$label // ""
$label
Truth table100%2/2
A
A= $label
Aresult
11
00
665 23 ▶ my $class = defined $node->{class} ? $c->('class', "$node->{class}=") : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $node->{'class'} ? : 0 23 23
666  
667 23 ▶ if ($node->{kind} eq 'hash') {
Branch: 4 branches
BranchTrueFalseTotal
if ($node->{'kind'} eq 'hash') { } 7 16 23
elsif ($node->{'kind'} eq 'array') { } 3 13 16
elsif ($node->{'kind'} eq 'sref') { } 5 8 13
elsif ($node->{'kind'} eq 'union') { } 0 8 8
668 7 my @k = sort keys %{ $node->{keys} };
669 7 ▶ my $count = $node->{wide} // scalar @k;
Condition50%1/2
$node->{"wide"} // scalar @k
l!l
07
MC/DC0%0/1
$node->{"wide"} // scalar @k
$node->{"wide"}
Truth table50%1/2
A
A= $node->{"wide"}
Aresult
11
00
670 7 ▶ push @{ $lines }, $pad . $class . $c->('HASH', "HASH{$count}")
Branch: 2 branches
BranchTrueFalseTotal
$node->{'n'} > 1 ? : 0 7 7
$node->{'wide'} ? : 0 7 7
671 . ($node->{n} > 1 ? " (from $node->{n} instances)" : '')
672 7 . ($node->{wide} ? ' ' . $c->('elem', '(keys merged)') : '');
673 7 for my $key (@k) {
674 9 my $entry = $node->{keys}{$key};
675 my $name = ($key eq '*' && $node->{wide})
676 ? $c->('elem', '<*>') . ': '
677 9 ▶ : $c->('key', $key) . ($entry->{optional} ? $c->('opt', '?') : '') . ': ';
Branch: 2 branches
BranchTrueFalseTotal
$key eq '*' && $node->{'wide'} ? : 0 9 9
$entry->{'optional'} ? : 0 9 9
Condition33%1/3
$key eq "*" and $node->{"wide"}
!ll&&!rl&&r
900
MC/DC0%0/2
$key eq "*" and $node->{"wide"}
$key eq "*" $node->{"wide"}
Truth table33%1/3
A and B
A= $key eq "*"B= $node->{"wide"}
ABresult
0X0
100
111
678 9 _structure_render($name, $entry->{node}, $indent + 1, $opt, $c, $lines);
679 }
680 }
681 elsif ($node->{kind} eq 'array') {
682 3 push @{ $lines }, $pad . $class . _structure_array_desc($node, $c);
683 3 ▶ if ($node->{node}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node->{'node'}) { } 3 0 3
684 3 _structure_render($c->('elem', '[*]') . ': ', $node->{node}, $indent + 1, $opt, $c, $lines);
685 } else {
686 0 push @{ $lines }, (' ' x ($indent + 1)) . $c->('elem', '(empty)');
687 }
688 }
689 elsif ($node->{kind} eq 'sref') { # \$x: stay on the same line, no extra indent level
690 # The '\ ' joins the label rather than the pad, and $indent passes
691 # through unchanged, so whatever the referent holds is still indented
692 # from this line. Passing $pad with indent 0 put the line right but
693 # dropped the referent's own children back to depth 1.
694 5 ▶ _structure_render(($label // '') . $class . $c->('elem', '\\') . ' ', $node->{node}, $indent, $opt, $c, $lines);
Condition100%2/2
$label // ""
l!l
41
MC/DC100%1/1
$label // ""
$label
Truth table100%2/2
A
A= $label
Aresult
11
00
695 }
696 elsif ($node->{kind} eq 'union') {
697 0 push @{ $lines }, $pad . $c->('UNION', 'UNION');
698 0 for my $alt (sort keys %{ $node->{alts} }) {
699 0 _structure_render($c->('elem', "<$alt>") . ' ', $node->{alts}{$alt}, $indent + 1, $opt, $c, $lines);
700 }
701 }
702 else { # leaf
703 8 push @{ $lines }, $pad . join($c->('elem', '|'),
704 8 map { $c->($_, $_) } sort keys %{ $node->{types} });
705 }
706 23 return;
707 }
708  
709 6 ▶sub structure {
Subroutine structure: called CC=12 SCAR=31.7
Pod documented
710 6 my ($ref, %args) = @_;
711 6 my %opt = (
712 output => 'stdout', # 'stdout' | 'stderr' | 'string' (string: return it, print nothing)
713 color => 'auto', # 'auto' | 1 | 0
714 max_depth => 0, # 0 = unlimited
715 hash_max => 32, # hashes wider than this collapse to one '<*>' entry; 0 = never
716 as => undef, # optional header line, like DDP's "as"
717 %args,
718 );
719 6 my %allowed = map { $_ => 1 } qw(output color max_depth hash_max as);
720 6 ▶ if (my @bad = grep { !$allowed{$_} } keys %opt) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@bad) = grep({not $allowed{$_};} keys %opt)) 0 6 6
721 0 die "Unrecognized arguments: @bad\nAccepted args: " . join(', ', sort keys %allowed);
722 }
723 6 ▶ 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 6 6
724  
725 6 require Scalar::Util; # ~4 ms (List::Util XS bootstrap); see header note
726  
727 6 ▶ my $fh = $opt{output} eq 'stderr' ? \*STDERR : \*STDOUT;
Branch: 1 branch
BranchTrueFalseTotal
$opt{'output'} eq 'stderr' ? : 0 6 6
728 my $use_color = $opt{color} eq 'auto'
729 ? ((($ENV{CLICOLOR_FORCE} || ($opt{output} ne 'string' && -t $fh)) && !$ENV{NO_COLOR}) ? 1 : 0)
730 6 ▶ : $opt{color};
Branch: 2 branches
BranchTrueFalseTotal
$opt{'color'} eq 'auto' ? : 0 6 6
($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
731 6 ▶ require Term::ANSIColor if $use_color; # ~0.8 ms, skipped entirely when piping
Branch: 1 branch
BranchTrueFalseTotal
if $use_color 0 6 6
732 6 ▶ my $c = sub { _structure_color($_[0], $_[1], $use_color) };
Subroutine __ANON__: called CC=1 SCAR=0.0
733  
734 6 my @lines;
735 6 ▶ push @lines, $c->('key', $opt{as}) if defined $opt{as};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt{"as"} 0 6 6
736 6 _structure_render(undef, _structure_describe([$ref], \%opt, 0, {}), 0, \%opt, $c, \@lines);
737 6 my $out = join("\n", @lines) . "\n";
738 0 ▶ print {$fh} $out unless $opt{output} eq 'string';
Branch: 1 branch
BranchTrueFalseTotal
unless $opt{"output"} eq "string" 0 6 6
739 6 return $out;
740 }
741  
742 # st(): structure() with DDP's calling convention, so you can write
743 #
744 # st %hash; st @array; st $ref; st %hash, max_depth => 2;
745 #
746 # instead of backslashing by hand. The \[@$%&] prototype makes perl pass a
747 # reference to the caller's variable, which is the whole trick -- but it also
748 # means the argument must BE a variable: st(\%h), st({...}) and
749 # st(func()) are compile-time errors, exactly as they are for DDP's p().
750 # Call structure() directly in those cases.
751 #
752 # NOTE: the obvious short name 's' is impossible. perl's tokenizer resolves a
753 # bare 's' to the substitution operator before it ever looks for a sub of that
754 # name, so `s $ref` dies with "Substitution pattern not terminated" and even
755 # `s($ref)` is parsed as s(pat)(repl). Only `&s($ref)` would work, which
756 # defeats the point. Hence 'st'.
757 1 ▶sub st (\[@$%&];%) {
Subroutine st: called CC=3 SCAR=13.3
Pod documented
758 1 my ($item, @args) = @_;
759 # `st %h` / `st @a` / `st &c` hand us the HASH/ARRAY/CODE ref directly, but
760 # `st $x` hands us a ref to the scalar $x -- one layer more than we want.
761 # The prototype rejects everything except a plain variable, so a SCALAR/REF
762 # here is always that added layer: peel exactly one. `st $hashref` then
763 # describes the hash, and `my $x = 42; st $x` prints 'number', not '\ number'.
764 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
765 1 return structure($ref, @args);
766 }
767  
768 86 1;
769 # from md2pod.pl πατερ ημων ο εν τοις ουρανοις, ἁγιασθήτω τὸ ὄνομά σου
770 =encoding utf8
771  
772 =head1 NAME
773  
774 Util::Cn - Small everyday helpers: directory listing, shell commands, JSON files, number formatting, and data-structure shapes
775  
776 =head1 Synopsis
777  
778 use Util::Cn;
779
780 my @scripts = dir(dir => '.', regex => '\.pl$', recursive => 1);
781 my $branch = execute('git rev-parse --abbrev-ref HEAD', 'stdout');
782 my $text = file2string('notes.txt');
783 print format_commas(1234567.891), "\n"; # 1,234,567.89
784
785 my $data = json_file_to_ref('results.json');
786 ref_to_json_file($data, 'copy.json');
787
788 st $data; # print the shape of $data, not its values
789 p $data; # Data::Printer's p(), loaded on first use
790  
791 =head1 Description
792  
793 C<Util::Cn> 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.
794  
795 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>.
796  
797 =head2 What C<use Util::Cn> does
798  
799 Besides exporting the ten functions below, C<use Util::Cn> does three things to the file and package that loads it:
800  
801 =over
802  
803 =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.
804  
805 =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.
806  
807 =item * It loads C<Devel::Confess>, which is process-wide: every C<die> and C<warn> in the program carries a stack trace.
808  
809 =back
810  
811 C<use Util::Cn ();> imports nothing and skips the first two; C<Devel::Confess> is still loaded. C<use Util::Cn 'format_commas';> imports only the names given, and still does all three.
812  
813 =head1 Functions
814  
815 All functions are exported by default.
816  
817 =head2 dir
818  
819 my @files = dir(dir => '/data', regex => '\.csv$');
820 my @tree = dir(dir => '/data', regex => '\.csv$', recursive => 1, cpu => 8);
821 dir(dir => '/data', recursive => 1, on_match => sub { say $_[0] });
822  
823 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.
824  
825 It takes these named arguments:
826  
827 =over
828  
829 =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.
830  
831 =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.
832  
833 =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.
834  
835 =item * C<recursive> (default C<0>): C<1> descends into subdirectories, through C<File::Find>, without following symbolic links.
836  
837 =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>.
838  
839 =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.
840  
841 =back
842  
843 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>.
844  
845 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.
846  
847 An unknown argument, a letter that is not a file test, a C<cpu> that is not a positive integer, and a directory that cannot be opened all die.
848  
849 =head2 execute
850  
851 my $exit = execute('make test'); # 0, or dies
852 my $out = execute('git log -1 --format=%H', 'stdout');
853 my $err = execute('perl -c script.pl', 'stderr');
854 my $all = execute('ls /nonexistent', 'all', 0); # does not die
855 # $all = { exit => 512, stdout => '', stderr => "ls: cannot access ..." }
856  
857 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:
858  
859 =over
860  
861 =item * C<exit> (the default): the wait status, C<$?> -- 0 for success, 256 for C<exit 1>
862  
863 =item * C<stdout>: standard output, chomped
864  
865 =item * C<stderr>: standard error, chomped
866  
867 =item * C<all>: a hash reference with C<exit>, C<stdout> and C<stderr>
868  
869 =back
870  
871 The third argument, C<$die>, is 1 by default: a command that exits non-zero prints its exit status, standard output and standard error to C<STDERR> and dies. Pass 0 to have the status returned instead.
872  
873 The command's standard input is the null device (C</dev/null>, or C<nul> on Windows). 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 restored afterwards.
874  
875 =head2 file2string
876  
877 my $text = file2string('notes.txt');
878  
879 Returns the whole of a file as one string, read without any decoding layer. A file that cannot be opened dies, naming it.
880  
881 =head2 format_commas
882  
883 format_commas(1234567.891); # '1,234,567.89'
884 format_commas(1234567, '%.0u'); # '1,234,567'
885 format_commas(999999.999); # '1,000,000.00'
886 format_commas(-0.5); # '-0.50'
887 format_commas(1e20); # '100,000,000,000,000,000,000.00'
888  
889 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.
890  
891 =head2 json_file_to_ref
892  
893 my $ref = json_file_to_ref('results.json');
894  
895 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 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.
896  
897 =head2 ref_to_json_file
898  
899 ref_to_json_file($data, 'results.json'); # prints "Wrote results.json"
900  
901 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 file name must be a plain string; a reference dies.
902  
903 =head2 random_key, random_value
904  
905 my $key = random_key(\%hash);
906 my $value = random_value(\%hash);
907  
908 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>.
909  
910 Both reset the hash's iterator, so do not call them on a hash in the middle of an C<each> loop.
911  
912 =head2 structure
913  
914 my $text = structure($ref, output => 'string');
915 structure(\%config, max_depth => 2, as => 'config');
916  
917 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.
918  
919 my @people = (
920 { name => 'Ann', age => 31, langs => ['perl', 'R'] },
921 { name => 'Bo', age => 28, langs => [], email => undef },
922 );
923 st @people;
924  
925 prints
926  
927 ARRAY[2]
928 [*]: HASH{4} (from 2 instances)
929 age: number
930 email?: null
931 langs: ARRAY[0-2] (from 2 instances)
932 [*]: string
933 name: string
934  
935 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 back to a containing structure is shown as C<(cycle)> rather than followed.
936  
937 It takes these options after the reference:
938  
939 =over
940  
941 =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.
942  
943 =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.
944  
945 =item * C<max_depth> (default C<0>): How many levels to descend before printing C<(...)>; C<0> is no limit.
946  
947 =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.
948  
949 =item * C<as> (no default): A line to print above the structure.
950  
951 =back
952  
953 =head2 st
954  
955 st %hash;
956 st @array;
957 st $ref, max_depth => 2;
958  
959 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.
960  
961 =head1 Installation
962  
963 cpanm Util::Cn
964  
965 or, from a copy of the repository:
966  
967 perl Makefile.PL
968 make
969 make test
970 make install
971  
972 =head1 Compatibility
973  
974 C<Util::Cn> 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; recursive listings with C<cpu> rely on C<Parallel::ForkManager>'s emulated C<fork>.
975  
976 =head1 Author
977  
978 David E. Condon L<mailto:dec986@gmail.com>
979  
980 =head1 License
981  
982 This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
983  
984 =head1 Thanks
985  
986 A lot of this work used Claude AI, which was paid for by the University of Idaho's IMCI
↑ Summary