blib/lib/P.pm

filter: Statementstmt 78.6% 180 / 229 Branchbran 57.1% 64 / 112 Conditioncond 33.3% 8 / 24 MC/DCmcdc 13.3% 2 / 15 Subroutinesub 83.7% 36 / 43 Podpod 0.0% 0 / 5 totaltotal 67.7% 290 / 428 CC 66 SCAR 29.2
CC
66
Cov
69%
P
70.0
Pe
20.0
Px
16.7
CRAP 18.5
↑ Summary
1 #!/usr/bin/perl -w
2 # vim=:SetNumberAndWidth
3  
4 =encoding utf-8
5  
6 =head1 NAME
7  
8 P - Safer, friendlier printf/print/sprintf + say
9  
10 =head1 VERSION
11  
12 Version "1.1.31"
13  
14 =cut
15  
16 { package P;
17 2 ▶ use warnings; use strict;use mem;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
18 2 our $VERSION='1.1.31';
19  
20 # RCS $Revision: 1.45 $ - $Date: 2015-12-14 12:09:03-08 $
21 # 1.1.31 - More pruning of bad test environments
22 # 1.1.30 - Attempt to prune unsupported OS's (WinXP)
23 # 1.1.29 - sprintf broken: include zero-width string spec to workaround
24 # 1.1.28 - testsuite fix - unknown failure case in sprintf:
25 # "Redundant argument in sprintf "... for "return sprintf $fmt, $v";
26 # Trying parens around sprintf($fmt, $v);
27 # (shot in dark for strawberry win32 perl on win10...)
28 # 1.1.27 - test fix -- Makefile.PL improperly specified "test", rather
29 # rather than using t/*.*t as pattern
30 # 1.1.26 - add code to allow changing defaults for literals and run-time
31 # constants previously only accessible through the OO method
32 # - Allow setting defaults globally as well as per-package
33 # - fix for bug in testcase 5 in "P.t" in some later versions
34 # of Strawberry Perl (5.22, 5.20?). Where the perlvar '$^X'
35 # contained a win32-backslash-separated path to perl. In double
36 # quotes, the backslashes are removed as literalizing the next
37 # character. Changing the path usage to not have double-quotes
38 # around the path should prevent the backslash-removal and pass
39 # the literal string to the perl 'system' call.
40 # 1.1.25 - put initial POD w/VERSION @ top to keep version #'s together
41 # - remove BEGIN that was needed for running/passing tests
42 # and instead use 'mem'
43 # - move changelog to column one and use vim markers to hide
44 # older changes
45 # - add dflts hash to allow 'use' time change of defaults (W.I.P.)
46 # - split local define+assignment ~#283 due to side effects
47 # 1.1.24 - respin for another Makefile change
48 # 1.1.23 - respin for a Makefile change
49 # 1.1.22 - respin to use alt version format
50 # 1.1.21 - respin to have BUID_REQ include more modern Ext:MM
51 # 1.1.20 - respin to have Makefile rely on Xporter 1.0.6
52 # 1.1.19 - Prereqs not being loaded in Cpantesters; attempt fix
53 # 1.1.18 - Unreported bugfix:
54 # the words HASH & ARRAY were sometimes printed in ref notation
55 # - remove included 'Types' code to use Types::Core (now published)
56 # 1.1.17 - Documentation refinements/fixes; Found possible culprit as to
57 # why Windows native tests could fail -- my source files in
58 # lib have pointed back to my real lib dir via a symlink.
59 # Windows wouldn't like those. Why any other platform did is
60 # likely some fluke of directory organization during test
61 # 1.1.16 - Different shot in dark to see if a change in P.env can make
62 # things work on Win-native
63 # 1.1.15 - Shot in dark to get 5.8.x to work(5.10 and newer seem to
64 # be working!
65 # 1.1.14 - and write out buffer from editor! (arg!)
66 # 1.1.13 - get perl w/ ^X rather than config
67 # 1.1.12 - Found another potential problem in the test prog.
68 # 1.1.11 - May have found another test bug.... trying fix for some fails
69 # 1.1.10 - Another internal format error bug (unreported), but caught
70 # in testing.
71 # 1.1.9 - Try to fix paths for test
72 # 1.1.8 - use ptar to generate Archive::tar compat archives
73 # 1.1.7 - Fix Makefile.PL
74 # 1.1.6 - Use t/P.env for premodifying ENV
75 # Document effect of printing to a FH & recording return val;
76 # 1.1.5 - Distribution change: use --format=v7 on tar to produce tarball
77 # (rt#90165)
78 # - Use shell script to preset env for test since
79 # Test::More doesn't set ENV
80 # 1.1.4 - Quick patch to enable use of state w/CORE::state
81 # 1.1.3 - [#$@%&!!!]
82 # 1.1.2 - Second try for test in P.t to get prereq's right
83 # 1.1.1 - Fix rest of (rt#89050)
84 # 1.1.0 - Fixed Internal bug#001, below & embedded \n@end of int. str
85 # (rt#89064)
86 # Version history continued... #{{{
87 # 1.0.32 - Fix double nest test case @{[\*STDERR, ["fmt:%s", "string"]]}
88 # (rt#89056)
89 # only use sprintf's numeric formats (e.g. %d, %f...) on
90 # numbers supported by sprintf (for now only arabic numerals).
91 # Otherwise print as string. (rt#89063)
92 # its numeric formats (ex "%d", "%f"...)
93 # 1.0.31 - Fix check for previously printed items to apply only to
94 # - the current output statement;
95 # 1.0.30 - Fix LF suppression -- instead of suppressing EOL, suppressed
96 # all output in the case where no FD was specified (code was
97 # confused in deciding whether or not to suppress output and
98 # return it as a string. (rt#89058)
99 # - Add missing quote in Synopsis (rt#89047)
100 # - Change NAME section to reference module following CPAN
101 # standard to re-list name of module instead of functions
102 # (rt#89046)
103 # - Fix L<> in POD that referenced "module" P::P instead of name, "P"
104 # (forms bad link in HTML) (rt#89051)
105 # - Since ($;@) prototypes cause more problems than (@), clean p
106 # proto's to use '@'; impliciation->remove array variations
107 # (rt@89052, #89055) (rt#89058)
108 # - fix outdated and inconsistent doc examples regarding old protos
109 # (rt#89056)(rt#89058)
110 # Had broken P's object oriented flag passing in adding
111 # the 'seen' function (to prevent recursive outptut. Fixed this
112 # while testing that main::DATA is properly closed (rt#89057,#89067)
113 # - Internal Bug #001
114 # #our @a = ("Hello %s", "World");
115 # #P(\*STDERR, \@a);
116 # # prints-> ARRAY(0x1003b40)
117 # 1.0.29 - Convert to using 'There does not exist' sign (∄), U+2204
118 # instead of (undef); use '🔁 ' for recursion/repeat;
119 # U+1F500
120 # 1.0.28 - When doing explicit out (FH specified), be sure to end
121 # with newln.
122 # 1.0.27 - DEFAULT change - don't do implicit IO reads (change via
123 # impicit_io option)
124 # - not usually needed in debugging or most output;
125 # could cause problems
126 # reading data from a file and causing desychronization problems;
127 # 1.0.26 - detect recursive data structs and don't expand them
128 # 1.0.25 - Add expansion for 'REF';
129 # - WIP: Trying to incorporate enumeration of duplicate adjacent
130 # data: Work In Progress: status: disabled
131 # 1.0.24 - limit default max string expanded to 140 chars (maybe want to
132 # do this only in brace expansions?) Method to change in OOO
133 # not documented at this time. NOTE: limiting output by default
134 # is not a great idea.
135 # 1.0.23 - When printing contents of a hash, print non-refs before
136 # refs, and print each subset in alpha sorted order
137 # 1.0.22 - Switch to {…} instead of HASH(0x12356892) or
138 # […] for arrays
139 # 1.0.21 - Doc change: added example of use in "die".
140 # 1.0.20 - Rewrite of testcase 5 in self-execution; no external progs
141 # anymore: use fork and print from P in perl child, then
142 # print from FH in parent, including uses of \x83 to
143 # inhibit extra LF's;
144 # 1.0.19 - Regretting fancy thru 'rev' P direct from FH test case (a bit)
145 # **seems** like some people don't have "." in path for test
146 # cases, so running "t/prog" doesn't work, trying "./t/prog"
147 # (1 fail on a Win32 base on a x64 system...so tempted
148 # to just ignore it...) >;^); guess will up this for now
149 # and think about that test case some more...
150 # I'm so gonna rewrite that case! (see xtodox below)
151 # 1.0.18 - convert top format-case statement to load-time compile
152 # and see if that helps BSD errors;
153 # - change test case w/array to use P & not old Pa-form
154 # - change test case to print to STDERR to use Pe
155 # - fix bug in decrement of $lvl in conditional (decrement must
156 # be in first part of conditional)
157 # - xtodox fix adaptation of 'rev' test case to work w/o
158 # separate file(done)
159 # 1.0.17 - another try at fixing pod decoding on metacpan
160 # 1.0.16 - pod '=encoding' move to before '=head'
161 # (ref:https://github.com/CPAN-API/metacpan-web/issues/800 )
162 # 1.0.15 - remove 'my $_' usage; old perl compat probs; use local
163 # in once instance were needed local copy of $_
164 # 1.0.14 - arg! misspelled Win nul: devname(fixed)
165 # 1.0.13 - test case change only to better test print to STDERR
166 # 1.0.12 - test case change: change of OBJ->print to print OBJ to
167 # try to get around problem on BSD5.12 in P.pm (worked!)
168 # - change embedded test case to not use util 'rev', but
169 # included perl script 'rev' in 't' directory...(for native win)
170 # 1.0.11 - revert printing decimals using %d: dropped significant leading
171 # zero's; Of NOTE: floating point output in objects is
172 # not default: we use ".2f"
173 # - left off space after comma in arrays(fixed)
174 # - rewrite of sections using given/when/default to not use
175 # them; try for 5.8 compat
176 # - call perl for invoking test vs. relying on #! invokation
177 # - pod updates mentioning 'ops'/depth
178 # 1.0.10 - remove Carp::Always from test (wasn't needed and caused it
179 # to fail on most test systems)
180 # add OO-oriented way to set internal P ops (to be documented)
181 # - fixed bug in logic trimming recursion depth on objects
182 # 1.0.9 - Add Px - recursive object print in squished form;
183 # Default to using Px for normal print
184 # 1.0.8 - fix when ref to IO -- wasn't dereferenced properly
185 # - upgrade of self-test/demo to allow specifying which test
186 # to run from cmd line; test numbers are taken from
187 # the displayed examples when run w/no arguments
188 # B:still doesn't run cleanly under test harness may need to
189 # change cases for that (Fixed)
190 # - POD update to current code
191 # 1.0.7 - (2013-1-9) add support for printing blessed objects
192 # - pod corrections
193 # - strip added LF from 'rev' example with tr (looks wrong)
194 # 1.0.6 - add manual check for LF at end (chomp doesn't always work)
195 # 1.0.5 - if don't recognize ref type, print var
196 # 1.0.4 - added support for printing contents of arrays and hashes.
197 # (tnx 2 MidLifeXis@prlmnks 4 brain reset)
198 # 1.0.3 - add Pea
199 # 1.0.2 - found 0x83 = "no break here" -- use that for NL suppress
200 # - added support for easy inclusion in other files
201 # (not just as lib);
202 # - add ISA and EXPORT to 'mem' so they are available @ BEGIN time
203 #
204 # 1.0.1 - add 0xa0 (non breaking space) to suppress NL
205 # #}}}
206  
207 2 ▶ use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
208 2 our (@ISA, @EXPORT);
209 # no sense to support iohandle w/Pe, as Pe is tied to stderr
210 2 ▶ { no warnings "once"; *IO::Handle::P = \&P::P }
Subroutine BEGIN: called CC=1 SCAR=0.0
211
212 2 ▶ use Types::Core;
Subroutine BEGIN: called CC=1 SCAR=0.0
213  
214 2 ▶ use mem(@EXPORT=qw(P Pe));
Subroutine BEGIN: called CC=1 SCAR=0.0
215 2 ▶ use Xporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
216  
217 2 my $ignore=<<'IGN' #{{{
218 BEGIN {
219 use constant EXPERIMENTAL=>0;
220  
221 if (EXPERIMENTAL) {
222 sub rm_adjacent {
223 my $c = 1;
224 ($a, $c) = @$a if ref $a;
225 $b //= "∄";
226 if ($a ne $b) { $c > 1 ? "$a × $c" : $a , $b }
227 else { (undef, [$a, ++$c]) }
228 }
229 sub reduce(&@) {
230 my (@final, $i) =((), 0);
231 my ($f, $ar)=@_;
232 for (my $i=0; $i < $#$ar; ++$i ) {
233 ($a, $b) = ($ar->[$i], $ar->[$i+1]);
234 my @r = &$f;
235 push @final, $r[0] if $r[0];
236 $ar->[$i+1] = $r[1];
237 }
238 @final;
239 }
240 }
241 }
242 IGN
243 ||undef; #}}}
244  
245
246  
247 2 ▶ use constant NoBrHr => 0x83; # Unicode codepoint="No Break Here"
Subroutine BEGIN: called CC=1 SCAR=0.0
248 2 our %_dflts;
249 2 our ($dflts, %mod_dflts, %types);
250 BEGIN {
251 2 ▶ %_dflts=(
Subroutine BEGIN: called CC=1 SCAR=0.4
252 implicit_io => 0,
253 depth => 3,
254 ellipsis => '…',
255 noquote => 1,
256 maxstring => undef,
257 seen => '🔁',
258 undef => '∄',
259 );
260  
261 2 ▶ my $bool = sub { $_[0] ? 1 : 0 };
Subroutine __ANON__: not called CC=2 SCAR=13.0
Branch: 1 branch
BranchTrueFalseTotal
$_[0] ? : 0 0 0
262 2 ▶ my $intnum = sub { $_[0] =~ m{^([0-9]+)$} ? 0 + $1 : 0 };
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ /^([0-9]+)$/ ? : 3 0 3
263 2 ▶ my $string = sub { length($_[0]) ? $_[0] : '' };
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
length $_[0] ? : 1 0 1
264 2 ▶ my $true = sub { 1 };
Subroutine __ANON__: not called CC=1 SCAR=1.2
265  
266 2 %types=(
267 default => $true,
268 depth => $intnum,
269 ellipsis => $string,
270 implicit_io => $bool,
271 maxstring => $intnum,
272 seen => $string,
273 undef => $string,
274 );
275  
276  
277 #global default copy
278 2 $mod_dflts{""} = \%_dflts;
279 2 $dflts = $mod_dflts{""};
280  
281 }
282  
283 sub sw(*);
284  
285 218 ▶ sub Px { my ($p, $v) = (shift, shift);
Subroutine Px: called CC=15 SCAR=28.1
Pod undocumented
286 218 ▶ local (*sw); *sw = sub (*) {$dflts->{$_[0]}};
Subroutine __ANON__: called CC=1 SCAR=0.0
287 218 ▶ if (ref $v) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v) 50 168 218
288 50 ▶ if ($p->{__P_seen}{$v}) { return "*". sw(seen) . ":" . $v . "*" }
Branch: 1 branch
BranchTrueFalseTotal
if ($p->{'__P_seen'}{$v}) { } 0 50 50
289 50 else {$p->{__P_seen}{$v} = 1}
290 }
291 218 ▶ my $lvl = scalar @_ ? $_[0] : 2;
Branch: 1 branch
BranchTrueFalseTotal
scalar @_ ? : 218 0 218
292 218 ▶ my $ro = scalar @_>1 ? $_[1]:0;
Branch: 1 branch
BranchTrueFalseTotal
scalar @_ > 1 ? : 155 63 218
293 218 ▶ return sw('undef') unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 9 209 218
294 209 my $ref = ref $v;
295 209 ▶ if (1 > $lvl-- || !$ref) {
Branch: 1 branch
BranchTrueFalseTotal
if (1 > $lvl-- or not $ref) { } 163 46 209
Condition100%3/3
1 > $lvl-- or not $ref
l!l&&r!l&&!r
669746
MC/DC100%2/2
1 > $lvl-- or not $ref
1 > $lvl-- not $ref
Truth table100%3/3
A or not(B)
A= 1 > $lvl--B= not $ref
ABresult
1X1
011
000
296 163 my $fmt; # prototypes are documentary (rt#89053)
297 163 ▶ my $given = [ sub ($$) { $_[0] =~ /^[-+]?[0-9]+\.?\z/ && q{%s} },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ /^[-+]?[0-9]+\.?\z/ and "%s" 68 95 163
298 95 ▶ sub ($$) { $_[1] && qq{%s}},
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_[1] and "%s" 68 27 95
299 27 ▶ sub ($$) { 1 == length($_[0]) && q{'%s'}},
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
1 == length $_[0] and "'%s'" 9 18 27
300 18 ▶ sub ($$) { $_[0] =~ m{^(?:[+-]?(?:\.[0-9]+)
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ /^(?:[+-]?(?:\.[0-9]+) | (?:[0-9]+\.[0-9]+))\z/x and "%.2f" 0 18 18
301 | (?:[0-9]+\.[0-9]+))\z}x && q{%.2f}},
302 18 ▶ sub ($$) { substr($_[0],0,5) eq 'HASH(' &&
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
substr($_[0], 0, 5) eq "HASH(" and '{' . &sw("ellipsis") . '}' . "%.0s" 4 14 18
303 '{'.sw(ellipsis).'}'.q{%.0s} },
304 14 ▶ sub ($$) { substr($_[0],0,6) eq 'ARRAY(' &&
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
substr($_[0], 0, 6) eq "ARRAY(" and '[' . &sw("ellipsis") . ']' . "%.0s" 0 14 14
305 '['.sw(ellipsis).']'.q{%.0s} },
306 # sub ($$) { $mxstr && length ($_[0])>$mxstr
307 # && qq("%.${mxstr}s")},
308 163 ▶ sub ($$) { 1 && q{"%s"}} ];
Subroutine __ANON__: called CC=1 SCAR=0.0
309  
310 163 ▶ do { $fmt = $_->($v, $ro) and last } for @$given;
Branch: 1 branch
BranchTrueFalseTotal
$fmt = &$_($v, $ro) and last 163 186 349
311 163 return sprintf($fmt, $v);
312 } else {
313 46 my $pkg = '';
314 46 ▶ ($pkg, $ref) = ($1, $2) if 0 <= (index $v,'=') && $v=~m{([\w:]+)=(\w+)};
Branch: 1 branch
BranchTrueFalseTotal
if index($v, "=") != -1 and $v =~ /([\w:]+)=(\w+)/ 0 46 46
Condition33%1/3
index($v, "=") != -1 and $v =~ /([\w:]+)=(\w+)/
!ll&&!rl&&r
4600
MC/DC0%0/2
index($v, "=") != -1 and $v =~ /([\w:]+)=(\w+)/
index($v, "=") != -1 $v =~ /([\w:]+)=(\w+)/
Truth table33%1/3
A and B
A= index($v, "=") != -1B= $v =~ /([\w:]+)=(\w+)/
ABresult
0X0
100
111
315 46 local * nonrefs_b4_refs ;
316 * nonrefs_b4_refs = sub {
317 51 ▶ ref $v->{$a} cmp ref $v->{$b} || $a cmp $b
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
ref $v->{$a} cmp ref $v->{$b} or $a cmp $b 42 9 51
318 46 };
319  
320 46 local (*IO_glob, *NIO_glob, *IO_io, *NIO_io);
321 (*IO_glob, *NIO_glob, *IO_io, *NIO_io) = (
322 0 ▶ sub(){'<*'.<$v>.'>'}, sub(){'<*='.$p->Px($v, $lvl-1).'>'},
Subroutine __ANON__: not called CC=1 SCAR=6.9
323 0 ▶ sub(){'<='.<$v>.'>'}, sub(){'<|'.$p->Px($v, $lvl-1).'|>'},
Subroutine __ANON__: not called CC=1 SCAR=6.9
324 46 );
325 2 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
326 my %actions = (
327 GLOB => ($p->{implicit_io}? *IO_glob: *NIO_glob),
328 IO => ($p->{implicit_io}? *IO_io : *NIO_io),
329 0 ▶ REF => sub(){ "\\" . $p->Px($$_, $lvl-1) . ' '},
Subroutine __ANON__: not called CC=1 SCAR=6.9
330 0 ▶ SCALAR=> sub(){ $pkg.'\\' . $p->Px($$_, $lvl).' ' },
Subroutine __ANON__: not called CC=1 SCAR=6.9
331 ARRAY => sub(){ $pkg."[".
332 (join ', ',
333 # not working: why? #reduce \&rm_adjacent, (commented out)
334 9 ▶ map{ $p->Px($_, $lvl) } @$v ) ."]" },
Subroutine __ANON__: called CC=1 SCAR=0.0
335 37 ▶ HASH => sub(){ $pkg.'{' . ( join ', ', @{[
Subroutine __ANON__: called CC=1 SCAR=0.0
336 37 map {$p->Px($_, $lvl, 1) . '=>'. $p->Px($v->{$_}, $lvl,0)}
337 46 ▶ sort nonrefs_b4_refs keys %$v]} ) . '}' },);
Branch: 2 branches
BranchTrueFalseTotal
$p->{'implicit_io'} ? : 0 46 46
$p->{'implicit_io'} ? : 0 46 46
338 46 ▶ if (my $act=$actions{$ref}) { &$act }
Branch: 1 branch
BranchTrueFalseTotal
if (my $act = $actions{$ref}) { } 46 0 46
339 0 else { return "$v" }
340 }
341 }
342  
343 sub get_dflts($) {
344 10 ▶ my $p = shift; my $caller = $_[0];
Subroutine get_dflts: called CC=3 SCAR=11.0
Pod undocumented
345 10 ▶ return $p->{dflts} if exists $p->{dflts};
Branch: 1 branch
BranchTrueFalseTotal
if exists $p->{"dflts"} 1 9 10
346 9 ▶ return exists $mod_dflts{$caller} ? $mod_dflts{$caller} : $mod_dflts{""};
Branch: 1 branch
BranchTrueFalseTotal
exists $P::mod_dflts{$caller} ? : 3 6 9
347 }
348
349  
350  
351 sub P(@) { # 'safen' to string or FH or STDOUT
352 9 ▶ local *sw = sub (*) {$dflts->{$_[0]}};
Subroutine P: called CC=20 SCAR=42.5
Subroutine __ANON__: called CC=1 SCAR=0.0
Pod undocumented
353 9 ▶ my $p = ref $_[0] eq 'P' ? shift: bless {};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'P' ? : 1 8 9
354 9 ▶ $p->{__P_seen}={} unless ref $p->{__P_seen};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $p->{"__P_seen"} 9 0 9
355  
356 local * unsee_ret = sub ($) {
357 9 ▶ delete $p->{__P_seen} if exists $p->{__P_seen};
Subroutine __ANON__: called CC=2 SCAR=7.1
Branch: 1 branch
BranchTrueFalseTotal
if exists $p->{"__P_seen"} 9 0 9
358 9 $_[0] };
359  
360 9 my $v = $_[0];
361 9 my $rv = ref $v;
362 9 $dflts = $p->get_dflts((caller)[0]);
363 9 my ($depth, $noquote) = (sw(depth), sw(noquote));
364 9 ▶ if (HASH eq $rv) {
Branch: 1 branch
BranchTrueFalseTotal
if (&HASH() eq $rv) 0 9 9
365 0 my $params = $v; $v = shift; $rv = ref $v;
366 0 ▶ $depth = $params->{depth} if exists $params->{depth};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params->{"depth"} 0 0 0
367 }
368 9 ▶ if (ARRAY eq $rv ) { $v = shift;
Branch: 1 branch
BranchTrueFalseTotal
if (&ARRAY() eq $rv) 0 9 9
369 0 @_=(@$v, @_); $v=$_[0]; $rv = ref $v }
370  
371 9 my ($fh, $f, $explicit_out);
372 9 ▶ if ($rv eq GLOB || $rv eq IO) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rv eq &GLOB() or $rv eq &IO()) { } 0 9 9
Condition33%1/3
$rv eq &GLOB() or $rv eq &IO()
l!l&&r!l&&!r
009
MC/DC0%0/2
$rv eq &GLOB() or $rv eq &IO()
$rv eq &GLOB() $rv eq &IO()
Truth table33%1/3
A or B
A= $rv eq &GLOB()B= $rv eq &IO()
ABresult
1X1
011
000
373 0 ($fh, $explicit_out) = (shift, 1);
374 0 $v = $_[0]; $rv = ref $v;
375 9 } else { $fh =\*STDOUT }
376
377 9 ▶ if (ARRAY eq $rv ) { $v = shift;
Branch: 1 branch
BranchTrueFalseTotal
if (&ARRAY() eq $rv) 0 9 9
378 0 @_=(@$v, @_); $v=$_[0]; $rv = ref $v }
379
380 9 my ($fc, $fmt, @flds, $res)=(1, $_[0]);
381 2 ▶ if ($fc) { $f = shift; no warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if ($fc) { } 9 0 9
382 9 $res = sprintf $f, map {local $_ = $p->Px($_,$depth,$noquote) } @_ }
383 0 else { $res = $p->Px(@_)}
384  
385 9 chomp $res;
386  
387 9 ▶ my ($nl, $ctx) = ("\n", defined wantarray ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
defined wantarray ? : 9 0 9
388  
389 9 ▶ ($res, $nl, $ctx) = (substr($res, 0, -1 + length $res), "", 2) if
Branch: 1 branch
BranchTrueFalseTotal
if ord substr($res, -1) == 131 0 9 9
390 ord(substr $res,-1) == NoBrHr; #"NO_BREAK_HERE"
391  
392 9 ▶ if (!$fh && !$ctx) { #internal consistancy check
Branch: 1 branch
BranchTrueFalseTotal
if (not $fh || $ctx) { } 0 9 9
Condition33%1/3
$fh || $ctx
l!l&&r!l&&!r
900
MC/DC0%0/2
$fh || $ctx
$fh $ctx
Truth table33%1/3
A || B
A= $fhB= $ctx
ABresult
1X1
011
000
393 0 ▶ ($fh = \*STDERR) and
Branch: 1 branch
BranchTrueFalseTotal
$fh = \*STDERR and $fh->P("Invalid File Handle presented for output, using STDERR") 0 0 0
394 P $fh "Invalid File Handle presented for output, using STDERR";
395 0 ($explicit_out, $nl) = (1, "\n") }
396  
397 9 ▶ else { return unsee_ret($res) if (!$explicit_out and $ctx==1) }
Branch: 1 branch
BranchTrueFalseTotal
if not $explicit_out and $ctx == 1 9 0 9
Condition33%1/3
not $explicit_out and $ctx == 1
!ll&&!rl&&r
009
MC/DC0%0/2
not $explicit_out and $ctx == 1
not $explicit_out $ctx == 1
Truth table33%1/3
not(A) and B
A= not $explicit_outB= $ctx == 1
ABresult
0X0
100
111
398  
399 2 ▶ no warnings 'utf8';
Subroutine BEGIN: called CC=1 SCAR=0.0
400 0 ▶ print $fh ($res . (!$ctx && (!$\ || $\ ne "\n") ? "\n" : "") );
Branch: 1 branch
BranchTrueFalseTotal
!$ctx && (!$\ || $\ ne "\n") ? : 0 0 0
Condition0%0/6
not $ctx and !$\ || $\ ne "\n"
!ll&&!rl&&r
000
not $\ or $\ ne "\n"
l!l&&r!l&&!r
000
MC/DC0%0/3
not $ctx and !$\ || $\ ne "\n"
not $ctx not $\ $\ ne "\n"
Truth table0%0/4
not(A) and not(B) or C
A= not $ctxB= not $\C= $\ ne "\n"
ABCresult
0XX0
1000
11X1
1011
401 0 unsee_ret($res);
402 };
403  
404 sub Pe(@) {
405 0 ▶ my $p = shift if ref $_[0];
Subroutine Pe: not called CC=4 SCAR=30.0
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
if ref $_[0] 0 0 0
406 0 ▶ return '' unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 0 0 0
407 0 unshift @_, \*STDERR;
408 0 ▶ unshift @_, $p if ref $p;
Branch: 1 branch
BranchTrueFalseTotal
if ref $p 0 0 0
409 0 goto &P
410 }
411  
412  
413 #Pe "_dflts=%s", \%_dflts;
414 #Pe "mod_dflts{}=%s", $mod_dflts{""};
415 #Pe "mod_dflts=%s", \%mod_dflts;
416  
417 sub import {
418 6 ▶ my ($modname, @args) = @_;
Subroutine import: called CC=11 SCAR=24.4
419 6 ▶ if (@args) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args) 4 2 6
420 4 my @others;
421 4 my $caller = (caller)[0];
422 4 ▶ if (exists $mod_dflts{$caller}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $P::mod_dflts{$caller}) { } 0 4 4
423 0 $dflts = $mod_dflts{$caller};
424 } else {
425 4 $dflts = undef; # indicate no customization to dflts
426 }
427 4 my $default = 0;
428 4 ▶ my @tags = grep { if (m{^:(.*)$}) {
Branch: 1 branch
BranchTrueFalseTotal
if (/^:(.*)$/) { } 5 0 5
429 5 ▶ if ($1 eq 'default') { $default = 1; $_ = undef }
Branch: 1 branch
BranchTrueFalseTotal
if ($1 eq 'default') { } 1 4 5
430 4 else { $_ = $1 }
431 0 } else { push @others, $_; undef }
432 } @args;
433 4 ▶ if (@tags) {
Branch: 1 branch
BranchTrueFalseTotal
if (@tags) 4 0 4
434 4 ▶ if ($default) {
Branch: 1 branch
BranchTrueFalseTotal
if ($default) { } 1 3 4
435 # change global defaults (don't use copy)
436 1 $dflts = $mod_dflts{""};
437 } else {
438 # if dflts was undef start w/copy of glbl-dflts
439 3 %{$mod_dflts{$caller}} = %{$mod_dflts{""}} unless exists
440 3 ▶ $mod_dflts{$caller};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $P::mod_dflts{$caller} 3 0 3
441 3 $dflts=$mod_dflts{$caller}
442 }
443 4 for (@tags) {
444 4 ▶ my ($tag, $value) = m{^(\w+)(?:=(.+))?$} or
Branch: 1 branch
BranchTrueFalseTotal
() = /^(\w+)(?:=(.+))?$/ or die q[Tag-format: missing :TAG=VALUE for tag '] . $_ . q['] 0 4 4
445 die "Tag-format: missing :TAG=VALUE for tag '" . $_ . "'";
446  
447 4 my $chk;
448 2 ▶ {no warnings; no strict; $chk = eval $types{$tag}->($value) };
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
449 4 $dflts->{$tag} = $chk;
450 }
451 }
452 4 ▶ $dflts = $mod_dflts{""} unless $dflts; # set to global if not set
Branch: 1 branch
BranchTrueFalseTotal
unless $P::dflts 0 4 4
453 4 @_=($modname, @others);
454 }
455 6 goto &Xporter::import;
456 }
457  
458  
459  
460  
461 sub ops($) {
462 1 ▶ my $p = shift; my $c=ref $p || $p;
Subroutine ops: called CC=7 SCAR=20.9
Pod undocumented
Condition33%1/3
ref $p || $p
l!l&&r!l&&!r
010
MC/DC0%0/2
ref $p || $p
ref $p $p
Truth table33%1/3
A || B
A= ref $pB= $p
ABresult
1X1
011
000
463 1 ▶ bless $p = {}, $c unless ref $p;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $p 1 0 1
464 1 my $args = $_[0];
465 1 my $ldflts = $p->get_dflts((caller)[0]);
466 1 ▶ %{$p->{dflts}} = %$dflts unless ref $p->{dflts};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $p->{"dflts"} 1 0 1
467 1 ▶ die "ops takes a hash to pass arguments" unless HASH $args;
Branch: 1 branch
BranchTrueFalseTotal
unless &HASH($args) 0 1 1
468 1 $ldflts = $p->{dflts};
469 1 foreach (sort keys %$args) {
470 1 ▶ if (exists $ldflts->{$_}) { $ldflts->{$_} = $args->{$_} }
Branch: 1 branch
BranchTrueFalseTotal
if (exists $ldflts->{$_}) { } 1 0 1
471 else {
472 0 warn "Unknown key \"$_\" passed to ops";}
473 }
474 1 $p }
475 2 1;} #value 1 placed at as w/most of my end-of-packages (rt#89054)
476  
477 {
478 2 package main;
479 2 ▶ use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
480  
481 2 ▶ unless ((caller 0)[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if ((caller 0)[0]) { } 2 0 2
482 0 binmode P::DATA, ":utf8";
483 0 binmode *STDOUT, ":utf8";
484 0 binmode *STDERR, ":utf8";
485 0 $_=do{ $/=undef, <P::DATA>};
486 0 close P::DATA;
487 0 our @globals;
488 0 eval $_;
489 0 ▶ die "self-test failed: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
490 0 1;
491 } else {
492 2 close P::DATA;
493 }
494 2 1;
495 }
496 ###########################################################################
497 # Pod documentation {{{1
498 # use P;
499  
500 =head1 SYNOPSIS
501  
502 use P qw[:depth=5 :undef=(undef)];
503  
504 P FILEHANDLE FORMAT, LIST
505 P FILEHANDLE LIST
506 P FORMAT, (LIST)
507 P (LIST)
508 P @ARRAY # can contain FH, FMT+ARGS & return string
509 $s = P @ARRAY; P $s; # can be same output as "P @ARRAY"
510 Pe # same as P STDERR,...
511 $s = P FILEHANDLE ... # sends same output to $s and FILEHANDLE
512  
513 =head1 DESCRIPTION
514  
515 C<P> is a combined print, printf, sprintf & say in 1 routine. It saves
516 tremendously on development time. It's not just the 1 char verb, but
517 has these time saving and powerful features:
518  
519 =over
520  
521 =item o B<No more switching between print, printf, sprintf, and say.>
522  
523 =back
524  
525 Too often I've either changed a string to a format statement, or just
526 forgot the 'f'. With C<P> it doesn't matter -- either will work.
527  
528 Example:
529 # Let's start with a "die" statement.
530 1) die "Wrong number of params";
531 # Then wants to add how many params one got:
532 2) die P "Expecting 2 params, got %s", scalar @ARGV;
533 # Then you want to see what was passed. No loop needed:
534 3) die P "Expecting 2 params, got %s (ARGV=%s), 0+@ARGV, \@ARGV;
535  
536  
537 In the send C<die>, C<P> is replacing C<sprintf> -- however, instead
538 of something like "C<ARRAY(0x12345678)>",
539 C<P> would try to display the actual contents of the array, showing
540 ["arg1", "arg2".
541  
542  
543 =over
544  
545 =item B<· Auto-Newline Handling>
546  
547 =back
548  
549 When it comes to C<newline>'s, or "\n" at the end of line, C<P>
550 behaves like C<say> when printing to output or a file handle and will
551 auto append a line feed when needed.
552  
553 Since C<P> can be used to print to strings, when doing so,
554 it will auto-suppress up to one included "C<\n>" at the end of a
555 format statement AND automatically add one if it is printing to a device
556 (if it is doing both at he same time -- it favors suppression).
557  
558 =over
559  
560 =item B<· Trapping C<undef>>
561  
562 =back
563  
564 How often have you printed diagnostic output only to get nothing
565 because one of the variables being printed was C<undef>. C<P> handles
566 it.
567  
568 By default, it prints a symbol for "does not exist" in place
569 of where the string would have displayed (%s fmt, only) and prints the
570 rest of the string normally.
571  
572 =over
573  
574 =item B<· Less restrictive syntax>
575  
576 =back
577  
578 C<P> doesn't have as many arbitrary restrictions on it's arguments.
579  
580 It handles cases that the equivalent perl statement won't.
581  
582  
583  
584 VERB -> P print printf sprintf say
585 V --FEATURE-- V --- ----- ------ ------- ---
586 to a FH Yes Yes Yes No Yes
587 to $fh Yes Yes Yes No No
588 to a string Yes No No Yes No
589 add EOL-NL to FH? Yes No No No Yes
590 sub EOL-NL w/"-l" Yes No No No Yes
591 sub EOL-NL in string Yes No No No No
592 FMT Yes No Yes Yes No
593 @[FMT,ARGS] Yes No Yes No No
594 undef to "%s" Yes No No No No
595 @[$fh,FMT,ARGS] (7) Yes No No No No
596 like "tee" (8) Yes No No No No
597  
598 7 - File Handle in 1st member of ARRAY used for output.
599  
600 8 - When P is being used as a string formatter like sprintf,
601 it can still have a "$fh" as the first argument that will
602 print the formatted string to the file handle as well as
603 returning it's value (note: this will force the string
604 to be printed w/o a trailing newline).
605  
606  
607  
608  
609 =head3 Undefs
610  
611  
612 When printed as strings (C<"%s">), undefs are automatically caught and
613 "E<0x2204>", (U+2204 - meaning "I<There does not exist>") is
614 printed in place of "C<Use of uninitialized value $x in xxx at -e line z.>"
615  
616 By default C<P>, prints the content of references (instead HASH
617 (or ARRAY)=(0x12345678), three levels deep. Deeper nesting is replaced
618 by the unicode ellipsis character (U+2026).
619  
620 While designed for development use, it is useful in many more situations, as
621 tries to "do the right thing" based on context. It can usually be used
622 as a drop-in replacement the perl functions C<print>, C<printf>, C<sprintf>,
623 and, C<say>.
624  
625 P tries to smartly handle newlines at the end of the line -- adding them
626 or subtracting them based on if they are going to a file handle or to another
627 variable.
628  
629 The newline handling at the end of a line can be supressed by adding
630 the Unicode control char "Don't break here" (0x83) at the end of a string
631 or by assigning the return value B<and> having a file handle as the first
632 argument. Ex: C<my $fmt = P STDOUT, "no LF added here--E<gt>">.
633  
634  
635 C<Bless>ed objects, by default, are printed with the Class or package name
636 in front of the reference. Note that these substitutions are performed only with
637 references printed through a string (C<"%s">) format -- features designed
638 to give useful output in development or debug situations.
639  
640 One minor difference between C<P> and C<sprintf>: C<P> can take
641 an array with the format in the 0th element, and parameters following.
642 C<Sprintf> will cause an error to be raised, if you try passing an array
643 to it, as it will force the array into scalar context -- which as
644 the manpage says "is almost never useful". Rather than follow in the
645 design flaws of its predecessors, P I<tries> to do the right thing.
646  
647  
648 B<NOTE:> A side effect of P being a contextual replacement for sprintf,
649 is if it is used as the last line of a subroutine. By default, this
650 won't print it's arguments to STDOUT unless you explicity specify the
651 filehandle, as it will think it is supposed to return the result -- not
652 print it.
653  
654  
655 =head2 Special Use Features
656  
657  
658 While C<P> is normally called procedurally, and not as an object, there are
659 some rare cases where one would really like it to print "just 1 level
660 deeper". To do that, you need to get a pointer to C<P>'s C<options>.
661  
662 To get that pointer, call C<P::-E<gt>ops({key=>value})> to set C<P>'s options and
663 save the return value. Use that pointer to call P. See following example.
664  
665 =head1 EXAMPLE: (changing P's defaults)
666  
667 Suppose you had an array of objects, and you wanted to see the contents
668 of the objects in the array. Normally P would only print the first two levels:
669  
670  
671 my %complex_probs = (
672 questions =E<gt> [ "sqrt(-4)", "(1-i)**2" ],
673 answers =E<gt> [ {real => 0, i =>2 },
674 {real => 0, i => -2 } ] );
675 my $prob_ref = \%complex_problems;
676 P "my probs = %s", [$prob_ref];
677  
678  
679 The above would normally produce:
680  
681 my probs = [{answers=>[{…}, {…}], questions=>["sqrt(-4)", "(1-i)**2"]}]
682  
683  
684 Instead of the contents of the hashes, P shows the ellipses (a
685 1 char-width wide character) for the interior of the hashes. If you
686 wanted the interior to print, you'd need to raise the default data
687 expansion I<depth> for C<P> as we do here:
688  
689  
690 my %complex_probs = (
691 questions => [ "sqrt(-4)", "(1-i)**2" ],
692 answers => [ {real => 0, i =>2 }, { real => 0, i => -2 } ] );
693 my $p=P::->ops({depth=>4});
694 $p->P("my array = %s", \%complex_probs);
695  
696  
697 The above allows 1 extra level of depth to be printed, so the elements in the
698 hash are displayed producing:
699  
700 my probs = [{answers=>[{i=>2, real=>0}, {i=>-2, real=>0}], # extra "\n"
701 questions=>["sqrt(-4)", "(1-i)**2"]}]
702  
703  
704 B<NOTE:> when referring to the B<package> B<C<P>>, a double colon is usually
705 needed to tell perl you are not talking about the function name.
706  
707 Please don't expect data printed by P to be "pretty" or parseable. It's not
708 meant to be a Perl::Tidy or Data::Dumper. I<Especially>, when printing
709 references, it was designed as a development aid.
710  
711  
712  
713 =head2 Summary of possible OO args to "ops" (and defaults)
714  
715 =over
716  
717 =item C<depth =E<gt> 3>
718  
719 =over
720  
721 Allows setting depth of nested structure printing. NOTE: regardless of depth,
722 recursive structures in the same call to C<P>, will not expand but be displayed
723 in an abbreviated form.
724  
725 =back
726  
727 =item C<implicit_io =E<gt> 0>
728  
729 =over
730  
731 When printing references, GLOBS and IO refs do not have their
732 contents printed (since printing contents of such refs may do I/O that
733 changes the object's state). If this is wanted, one would call C<ops> with C<implicit_io> set to true (1).
734  
735 =back
736  
737 =item C<noquote =E<gt> 1>
738  
739 =over
740  
741 In printing items in hashes or arrays, data that are Read-Only or do not need
742 quoting won't have quoting (contrast to Data::Dumper, where it can be turned
743 off or on, but not turned on, only when needed).
744  
745 =back
746  
747 =item C<maxstring =E<gt> undef>
748  
749 =over 2
750  
751 Allows specifying a maximum length of any single datum when expanded from an indirection expansion.
752  
753 =back
754  
755 =back
756  
757 =head2 Example 2: Not worrying about "undefs"
758  
759 Looking at some old code of mine, I found this:
760  
761 print sprintf STDERR,
762 "Error: in parsing (%s), proto=%s, host=%s, page=%s\n",
763 $_[0] // "null", $proto // "null", $host // "null",
764 $path // "null";
765 die "Exiting due to error."
766  
767 Too many words and effort in upgrading a die message! Now it looks like:
768  
769 die P "Error: in parsing (%s), proto=%s, host=%s, page=%s",
770 $_[0], $proto, $host, $path;
771  
772 It's not just about formatting or replacing sprintf -- but automatically
773 giving you sanity in places like error messages and debug output when
774 the variables you are printing may be 'undef' -- which would abort the
775 output entirely!
776  
777  
778  
779 =head1 MORE EXAMPLES
780  
781  
782 P "Hello %s", "World"; # auto NL when to a FH
783 P "Hello \x83"; P "World"; # \x83: suppress auto-NL to FH's
784 $s = P "%s", "Hello %s"; # not needed if printing to string
785 P $s, "World"; # still prints "Hello World"
786  
787 @a = ("Hello %s", "World"); # using array, fmt as 1st arg
788 P @a; # print "Hello World"
789 P 0 + @a; # prints #items in '@a': 2
790  
791 P "a=%s", \@a; # prints contents of 'a': [1,2,3...]
792  
793 P STDERR @a # use @a as args to a specific FH
794 # Uses indirect method calls when
795 # invoked like "print FH ARGS"
796 #
797 Pe "Output to STDERR" # 'Shortcut' for P to STDERR
798  
799 %H=(one=>1, two=>2, u=>undef); # P Hash bucket usage + contents:
800  
801 P "%H hash usage: %s", "".%H; # Shows used/total Hash bucket usage
802 P "%H=%s", \%H; # print contents of hash:
803  
804 %H={u=>(undef), one=>1, two=>2}
805  
806 bless my $h=\%H, 'Hclass'; # Blessed objects...
807 P "Obj_h = %s", $h; # & content:
808  
809 Obj_h = Hclass{u=>(undef), one=>1, two=>2}
810  
811  
812 =head1 NOTES
813  
814 Values given as args with a format statement, are
815 checked for B<undef> and have "E<0x2204>" substituted for undefined values.
816 If you print vars as in decimal or floating point, they'll likely show up
817 as 0, which doesn't stand out as well.
818  
819 Sometimes the perl parser gets confused about what args belong to P and
820 which do not. Using parentheses (I<ex.> C<P("Hello World")>) can help in those
821 cases.
822  
823 Usable in any code, P was was designed to save typing, time
824 and work of undef checking, newline handling, peeking at data
825 structures in small spaces during development. It tries to do
826 the "right thing" with the given input. It may not be
827 suitable where speed is paramount.
828  
829 =cut
830 #}}}1
831  
832 package P;
833 __DATA__
↑ Summary