Tools.pm

filter: Statementstmt 97.1% 669 / 689 Branchbran 77.3% 243 / 314 Conditioncond 62.1% 59 / 95 MC/DCmcdc 44.8% 26 / 58 Subroutinesub 96.8% 123 / 127 Podpod 0.9% 1 / 104 totaltotal 80.8% 1121 / 1387 CC 227 SCAR 20.4
CC
227
Cov
88%
hash_validate
23.2
format_ascii_table
23.0
hash_fingerprint
20.0
CRAP 7.7
↑ Summary Tools/CSV.pm »
1 ##############################################################################
2 #
3 # Data::Tools perl module
4 # Copyright (c) 2013-2024 Vladi Belperchinov-Shabanski "Cade"
5 # <cade@noxrun.com> <cade@bis.bg> <cade@cpan.org>
6 # http://cade.noxrun.com/
7 #
8 # GPL
9 #
10 ##############################################################################
11 package Data::Tools;
12 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 3 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 3 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 3 ▶use Storable;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 3 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 3 ▶use Digest;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 3 ▶use Digest::Whirlpool;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 3 ▶use Digest::MD5;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 3 ▶use Digest::SHA1;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 3 ▶use MIME::Base64;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 3 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 3 ▶use File::Glob;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 3 ▶use Hash::Util qw( lock_hashref unlock_hashref lock_ref_keys );
Subroutine BEGIN: called CC=1 SCAR=0.0
25 3 ▶use Fcntl qw( :flock );
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27 3 our $VERSION = '1.60';
28  
29 3 our @ISA = qw( Exporter );
30 3 our @EXPORT = qw(
31  
32 data_tools_set_text_io_encoding
33 data_tools_set_text_io_utf8
34 data_tools_set_text_io_bin
35  
36 file_save
37 file_load
38 file_load_ar
39  
40 file_bin_save
41 file_bin_load
42  
43 file_text_save
44 file_text_append
45 file_text_load
46 file_text_load_ar
47 file_text_load_first_line
48  
49 cmd_read_from
50 cmd_write_to
51  
52 file_mtime
53 file_ctime
54 file_atime
55 file_size
56  
57 file_path
58 file_name
59 file_name_ext
60 file_ext
61  
62 file_lock
63 file_lock_nb
64 file_lock_ex
65 file_lock_ex_nb
66 file_unlock
67  
68 dir_path_make
69 dir_path_ensure
70  
71 str2hash
72 hash2str
73 hash2str_keys
74  
75 str2hash_url
76 hash2str_url
77 url2hash
78  
79 hash2json
80 hash2json_pp
81 hash2json_cc
82 json2hash
83  
84 hash_uc
85 hash_lc
86 hash_uc_ipl
87 hash_lc_ipl
88  
89 hash_save
90 hash_load
91 hash_save_keys
92 hash_save_url
93 hash_load_url
94 hash_save_json
95 hash_save_json_pp
96 hash_load_json
97  
98 hash_fingerprint
99 hash_validate
100  
101 hash_lock_recursive
102 hash_unlock_recursive
103 hash_keys_lock_recursive
104  
105 hr_traverse_vals
106 ar_traverse_vals
107  
108 list_uniq
109  
110 str_escape
111 str_unescape
112  
113 str_url_escape
114 str_url_unescape
115  
116 str_html_escape
117 str_html_escape_text
118 str_html_escape_attr
119 str_html_unescape
120  
121 str_hex
122 str_unhex
123  
124 str_hex_utf8
125 str_unhex_utf8
126  
127 str_num_comma
128 str_pad
129 str_pad_center
130 str_countable
131  
132 str_kmg_to_num
133 str_hms_to_secs
134  
135 str_password_strength
136  
137 str_capitalize
138  
139 str_initials
140  
141 perl_package_to_file
142  
143 wp_hex
144 md5_hex
145 sha1_hex
146  
147 wp_hex_file
148 md5_hex_file
149 sha1_hex_file
150  
151 create_random_id
152 create_random_binary
153  
154 glob_tree
155 read_dir_entries
156  
157 fftwalk
158  
159 FFT_FILES
160 FFT_DIRS
161  
162 FFT_SYMF
163 FFT_SYMD
164  
165 FFT_FOLLOW
166 FFT_DEBUG
167  
168 FFT_ALL
169 FFT_ALL4
170 FFT_FULL
171  
172 ref_freeze
173 ref_thaw
174  
175 int2hex
176 hex2int
177  
178 bcd2int
179 int2bcd
180 bcd2str
181  
182 format_ascii_table
183  
184 eval_err_strip
185 );
186  
187 3 our %EXPORT_TAGS = (
188  
189 'all' => \@EXPORT,
190 'none' => [],
191  
192 );
193  
194 ##############################################################################
195  
196 3 my $TEXT_IO_ENCODING;
197  
198 sub data_tools_set_text_io_encoding
199 4 ▶{
Subroutine data_tools_set_text_io_encoding: called CC=2 SCAR=6.9
Pod undocumented
200 4 $TEXT_IO_ENCODING = shift;
201 4 ▶ die "invalid text files io encoding [$TEXT_IO_ENCODING]" unless $TEXT_IO_ENCODING =~ /^[a-z_0-9:\-]*$/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $TEXT_IO_ENCODING =~ /^[a-z_0-9:\-]*$/i 1 3 4
202 }
203  
204 sub data_tools_set_text_io_utf8
205 1 ▶{
Subroutine data_tools_set_text_io_utf8: called CC=1 SCAR=0.0
Pod undocumented
206 1 data_tools_set_text_io_encoding( 'UTF-8' );
207 }
208  
209 sub data_tools_set_text_io_bin
210 2 ▶{
Subroutine data_tools_set_text_io_bin: called CC=1 SCAR=0.0
Pod undocumented
211 2 data_tools_set_text_io_encoding( undef );
212 }
213  
214 ##############################################################################
215 # the old interface, still works but will be removed!
216  
217 sub file_load
218 6 ▶{
Subroutine file_load: called CC=8 SCAR=21.1
Pod undocumented
219 6 my $fn = shift; # file name
220 6 ▶ my $opt = shift || {};
Condition50%1/2
shift() || {}
l!l
06
MC/DC0%0/1
shift() || {}
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
221  
222 6 ▶ if( ref( $fn ) eq 'HASH' )
Branch: 1 branch
BranchTrueFalseTotal
if (ref $fn eq 'HASH') { } 1 5 6
223 {
224 1 $opt = $fn;
225 1 hash_uc_ipl( $opt );
226 1 ▶ $fn = $opt->{ 'FNAME' } || $opt->{ 'FILE_NAME' };
Condition33%1/3
$opt->{'FNAME'} || $opt->{'FILE_NAME'}
l!l&&r!l&&!r
010
MC/DC0%0/2
$opt->{'FNAME'} || $opt->{'FILE_NAME'}
$opt->{'FNAME'} $opt->{'FILE_NAME'}
Truth table33%1/3
A || B
A= $opt->{'FNAME'}B= $opt->{'FILE_NAME'}
ABresult
1X1
011
000
227 }
228 else
229 {
230 5 hash_uc_ipl( $opt );
231 }
232  
233 6 my $i;
234 6 my $encoding = $opt->{ 'ENCODING' };
235 6 my $mopt;
236 6 ▶ $mopt = ":encoding($encoding)" if $encoding;
Branch: 1 branch
BranchTrueFalseTotal
if $encoding 1 5 6
237 6 ▶ open( $i, "<" . $mopt, $fn ) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
open $i, '<' . $mopt, $fn or return undef 5 1 6
238 5 ▶ flock( $i, LOCK_SH ) if $opt->{ 'FLOCK' };
Branch: 1 branch
BranchTrueFalseTotal
if $opt->{"FLOCK"} 0 5 5
239 5 ▶ binmode( $i ) if $opt->{ ':RAW' };
Branch: 1 branch
BranchTrueFalseTotal
if $opt->{":RAW"} 0 5 5
240 5 local $/ = undef;
241 5 my $s = <$i>;
242 5 close $i;
243 5 return $s;
244 }
245  
246 sub file_load_ar
247 1 ▶{
Subroutine file_load_ar: called CC=8 SCAR=24.3
Pod undocumented
248 1 my $fn = shift; # file name
249 1 ▶ my $opt = shift || {};
Condition50%1/2
shift() || {}
l!l
01
MC/DC0%0/1
shift() || {}
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
250  
251 1 ▶ if( ref( $fn ) eq 'HASH' )
Branch: 1 branch
BranchTrueFalseTotal
if (ref $fn eq 'HASH') { } 0 1 1
252 {
253 0 $opt = $fn;
254 0 hash_uc_ipl( $opt );
255 0 ▶ $fn = $opt->{ 'FNAME' } || $opt->{ 'FILE_NAME' };
Condition0%0/3
$opt->{'FNAME'} || $opt->{'FILE_NAME'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$opt->{'FNAME'} || $opt->{'FILE_NAME'}
$opt->{'FNAME'} $opt->{'FILE_NAME'}
Truth table0%0/3
A || B
A= $opt->{'FNAME'}B= $opt->{'FILE_NAME'}
ABresult
1X1
011
000
256 }
257 else
258 {
259 1 hash_uc_ipl( $opt );
260 }
261  
262 1 my $i;
263 1 my $encoding = $opt->{ 'ENCODING' };
264 1 my $mopt;
265 1 ▶ $mopt = ":encoding($encoding)" if $encoding;
Branch: 1 branch
BranchTrueFalseTotal
if $encoding 0 1 1
266 1 ▶ open( $i, "<" . $mopt, $fn ) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
open $i, '<' . $mopt, $fn or return undef 1 0 1
267 1 ▶ flock( $i, LOCK_SH ) if $opt->{ 'FLOCK' };
Branch: 1 branch
BranchTrueFalseTotal
if $opt->{"FLOCK"} 0 1 1
268 1 ▶ binmode( $i ) if $opt->{ ':RAW' };
Branch: 1 branch
BranchTrueFalseTotal
if $opt->{":RAW"} 0 1 1
269 1 my @all = <$i>;
270 1 close $i;
271 1 return \@all;
272 }
273  
274 # FIXME: TODO: add umask
275 sub file_save
276 11 ▶{
Subroutine file_save: called CC=9 SCAR=23.9
Pod undocumented
277 11 my $fn = shift; # file name
278  
279 11 my $opt = {};
280 11 ▶ if( ref( $fn ) eq 'HASH' )
Branch: 1 branch
BranchTrueFalseTotal
if (ref $fn eq "HASH") 1 10 11
281 {
282 1 $opt = $fn;
283 1 hash_uc_ipl( $opt );
284 1 ▶ $fn = $opt->{ 'FNAME' } || $opt->{ 'FILE_NAME' };
Condition33%1/3
$opt->{'FNAME'} || $opt->{'FILE_NAME'}
l!l&&r!l&&!r
010
MC/DC0%0/2
$opt->{'FNAME'} || $opt->{'FILE_NAME'}
$opt->{'FNAME'} $opt->{'FILE_NAME'}
Truth table33%1/3
A || B
A= $opt->{'FNAME'}B= $opt->{'FILE_NAME'}
ABresult
1X1
011
000
285 }
286  
287 11 my $encoding = $opt->{ 'ENCODING' };
288 11 my $mopt;
289 11 ▶ $mopt = ":encoding($encoding)" if $encoding;
Branch: 1 branch
BranchTrueFalseTotal
if $encoding 1 10 11
290  
291 11 my $o;
292 # FIXME: with FLOCK, ">" empties the file before flock() below, so a reader can
293 # get an empty file in that window; open with ">>", then flock(), then
294 # truncate() to close it
295 11 ▶ open( $o, ">" . $mopt, $fn ) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
open $o, '>' . $mopt, $fn or return undef 11 0 11
296 11 ▶ if( $opt->{ 'FLOCK' } )
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"FLOCK"}) 0 11 11
297 {
298 0 flock( $o, LOCK_EX );
299 0 truncate( $o, 0 ); # need to clear file if race but after lock
300 }
301 11 ▶ binmode( $o ) if $opt->{ ':RAW' };
Branch: 1 branch
BranchTrueFalseTotal
if $opt->{":RAW"} 0 11 11
302 11 ▶ return undef unless print( $o @_ ) and close( $o );
Branch: 1 branch
BranchTrueFalseTotal
unless print $o @_ and close $o 0 11 11
Condition33%1/3
print $o @_ and close $o
!ll&&!rl&&r
0011
MC/DC0%0/2
print $o @_ and close $o
print $o @_ close $o
Truth table33%1/3
A and B
A= print $o @_B= close $o
ABresult
0X0
100
111
303 11 return 1;
304 }
305  
306 ##############################################################################
307 # binary files load/save
308  
309 sub file_bin_load
310 1 ▶{
Subroutine file_bin_load: called CC=2 SCAR=7.0
Pod undocumented
311 1 my $fn = shift; # file name
312  
313 1 my $i;
314 1 ▶ open( $i, "<", $fn ) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
open $i, "<", $fn or return undef 1 0 1
315 1 binmode( $i );
316 1 local $/ = undef;
317 1 my $s = <$i>;
318 1 close $i;
319 1 return $s;
320 }
321  
322 sub file_bin_save
323 3 ▶{
Subroutine file_bin_save: called CC=4 SCAR=13.9
Pod undocumented
324 3 my $fn = shift; # file name
325  
326 3 my $o;
327 #- open( $o, ">", $fn ) or return 0; # cc20261026-14
328 3 ▶ open( $o, ">", $fn ) or return undef; # cc20261026-14
Branch: 1 branch
BranchTrueFalseTotal
open $o, ">", $fn or return undef 2 1 3
329 2 binmode( $o );
330 #- print $o @_; # cc20261026-14
331 #- close $o; # cc20261026-14
332 2 ▶ return undef unless print( $o @_ ) and close( $o ); # a full disk fails here, as file_save() # cc20261026-14
Branch: 1 branch
BranchTrueFalseTotal
unless print $o @_ and close $o 1 1 2
Condition66%2/3
print $o @_ and close $o
!ll&&!rl&&r
101
MC/DC50%1/2
print $o @_ and close $o
print $o @_ close $o
Truth table66%2/3
A and B
A= print $o @_B= close $o
ABresult
0X0
100
111
333 1 return 1;
334 }
335  
336 ##############################################################################
337 # text files load/save
338  
339 sub file_text_load
340 4 ▶{
Subroutine file_text_load: called CC=5 SCAR=16.3
Pod undocumented
341 4 my $fn = shift; # file name
342 4 my $opt = shift;
343  
344 4 my $i;
345 4 ▶ my $enc = ":encoding($TEXT_IO_ENCODING)" if $TEXT_IO_ENCODING;
Branch: 1 branch
BranchTrueFalseTotal
if $TEXT_IO_ENCODING 0 4 4
346 4 ▶ open( $i, "<$enc", $fn ) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
open $i, "<$enc", $fn or return undef 4 0 4
347 4 ▶ binmode( $i ) unless $TEXT_IO_ENCODING;
Branch: 1 branch
BranchTrueFalseTotal
unless $TEXT_IO_ENCODING 4 0 4
348 4 ▶ local $/ = undef unless $opt->{ 'FIRST_LINE_ONLY' };
Branch: 1 branch
BranchTrueFalseTotal
unless $opt->{"FIRST_LINE_ONLY"} 3 1 4
349 4 my $s = <$i>;
350 4 close $i;
351 4 return $s;
352 }
353  
354 sub file_text_load_ar
355 1 ▶{
Subroutine file_text_load_ar: called CC=4 SCAR=14.2
Pod undocumented
356 1 my $fn = shift; # file name
357  
358 1 my $i;
359 1 ▶ my $enc = ":encoding($TEXT_IO_ENCODING)" if $TEXT_IO_ENCODING;
Branch: 1 branch
BranchTrueFalseTotal
if $TEXT_IO_ENCODING 0 1 1
360 1 ▶ open( $i, "<$enc", $fn ) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
open $i, "<$enc", $fn or return undef 1 0 1
361 1 ▶ binmode( $i ) unless $TEXT_IO_ENCODING;
Branch: 1 branch
BranchTrueFalseTotal
unless $TEXT_IO_ENCODING 1 0 1
362 1 my @a = <$i>;
363 1 close $i;
364 1 return \@a;
365 }
366  
367 sub file_text_load_first_line
368 1 ▶{
Subroutine file_text_load_first_line: called CC=1 SCAR=0.0
Pod undocumented
369 1 return file_text_load( shift(), { 'FIRST_LINE_ONLY' => 1 } );
370 }
371  
372 sub file_text_save
373 4 ▶{
Subroutine file_text_save: called CC=6 SCAR=18.2
Pod undocumented
374 4 my $fn = shift; # file name
375  
376 4 my $o;
377 #- my $enc = ":encoding($TEXT_IO_ENCODING)" if $TEXT_IO_ENCODING; # cc20261026-14
378 #- open( $o, ">$enc", $fn ) or return 0; # cc20261026-14
379 4 ▶ my $enc = $TEXT_IO_ENCODING ? ":encoding($TEXT_IO_ENCODING)" : ''; # cc20261026-14 no "my ... if"
Branch: 1 branch
BranchTrueFalseTotal
$TEXT_IO_ENCODING ? : 0 4 4
380 4 ▶ open( $o, ">$enc", $fn ) or return undef; # cc20261026-14
Branch: 1 branch
BranchTrueFalseTotal
open $o, ">$enc", $fn or return undef 3 1 4
381 3 ▶ binmode( $o ) unless $TEXT_IO_ENCODING;
Branch: 1 branch
BranchTrueFalseTotal
unless $TEXT_IO_ENCODING 3 0 3
382 #- print $o @_; # cc20261026-14
383 #- close $o; # cc20261026-14
384 3 ▶ return undef unless print( $o @_ ) and close( $o ); # a full disk fails here, as file_save() # cc20261026-14
Branch: 1 branch
BranchTrueFalseTotal
unless print $o @_ and close $o 1 2 3
Condition66%2/3
print $o @_ and close $o
!ll&&!rl&&r
102
MC/DC50%1/2
print $o @_ and close $o
print $o @_ close $o
Truth table66%2/3
A and B
A= print $o @_B= close $o
ABresult
0X0
100
111
385 2 return 1;
386 }
387  
388 sub file_text_append
389 1 ▶{
Subroutine file_text_append: called CC=4 SCAR=14.2
Pod undocumented
390 1 my $fn = shift; # file name
391  
392 1 my $o;
393 1 ▶ my $enc = ":encoding($TEXT_IO_ENCODING)" if $TEXT_IO_ENCODING;
Branch: 1 branch
BranchTrueFalseTotal
if $TEXT_IO_ENCODING 0 1 1
394 1 ▶ open( $o, ">>$enc", $fn ) or return 0;
Branch: 1 branch
BranchTrueFalseTotal
open $o, ">>$enc", $fn or return 0 1 0 1
395 1 ▶ binmode( $o ) unless $TEXT_IO_ENCODING;
Branch: 1 branch
BranchTrueFalseTotal
unless $TEXT_IO_ENCODING 1 0 1
396 1 print $o @_;
397 1 close $o;
398 1 return 1;
399 }
400  
401 ##############################################################################
402  
403 sub cmd_read_from
404 1 ▶{
Subroutine cmd_read_from: called CC=3 SCAR=11.2
Pod undocumented
405 1 my $cmd = shift;
406  
407 1 ▶ my @cmd = ref( $cmd ) ? @$cmd : ( $cmd );
Branch: 1 branch
BranchTrueFalseTotal
ref $cmd ? : 0 1 1
408  
409 1 ▶ open( my $i, "-|", @cmd ) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
open my $i, "-|", @cmd or return undef 1 0 1
410 1 local $/ = undef;
411 1 my $s = <$i>;
412 1 close $i;
413 1 return $s;
414 }
415  
416 sub cmd_write_to
417 0 ▶{
Subroutine cmd_write_to: not called CC=3 SCAR=24.8
Pod undocumented
418 0 my $cmd = shift;
419  
420 0 ▶ my @cmd = ref( $cmd ) ? @$cmd : ( $cmd );
Branch: 1 branch
BranchTrueFalseTotal
ref $cmd ? : 0 0 0
421  
422 0 ▶ open( my $o, "|-", @cmd ) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
open my $o, "|-", @cmd or return undef 0 0 0
423 0 print $o @_;
424 0 close $o;
425 0 return 1;
426 }
427  
428 ##############################################################################
429  
430 sub file_mtime
431 1 ▶{
Subroutine file_mtime: called CC=1 SCAR=0.0
Pod undocumented
432 1 return (stat(shift))[9];
433 }
434  
435 sub file_ctime
436 1 ▶{
Subroutine file_ctime: called CC=1 SCAR=0.0
Pod undocumented
437 1 return (stat(shift))[10];
438 }
439  
440 sub file_atime
441 1 ▶{
Subroutine file_atime: called CC=1 SCAR=0.0
Pod undocumented
442 1 return (stat(shift))[8];
443 }
444  
445 sub file_size
446 1 ▶{
Subroutine file_size: called CC=1 SCAR=0.0
Pod undocumented
447 1 return (stat(shift))[7];
448 }
449  
450 ##############################################################################
451  
452 sub file_path
453 1 ▶{
Subroutine file_path: called CC=2 SCAR=7.6
Pod undocumented
454 1 ▶ return $_[0] =~ /((^|.*?)\/)([^\/]*)$/ ? $1 : undef;
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ m[((^|.*?)/)([^/]*)$] ? : 1 0 1
455 }
456  
457 sub file_name
458 3 ▶{
Subroutine file_name: called CC=2 SCAR=7.6
Pod undocumented
459 # return full name with leadeing dot for dot-files ( .filename )
460 3 ▶ return $_[0] =~ /(^|\/)([^\/]+?)(\.([^\.\/]+))?$/ ? $2 : undef;
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ m[(^|/)([^/]+?)(\.([^\./]+))?$] ? : 3 0 3
461 }
462  
463 sub file_name_ext
464 2 ▶{
Subroutine file_name_ext: called CC=2 SCAR=7.6
Pod undocumented
465 # return full name with leadeing dot for dot-files ( .filename )
466 2 ▶ return $_[0] =~ /(^|\/)([^\/]+)$/ ? $2 : undef;
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ m[(^|/)([^/]+)$] ? : 2 0 2
467 }
468  
469 sub file_ext
470 2 ▶{
Subroutine file_ext: called CC=2 SCAR=6.9
Pod undocumented
471 # return undef for dot-files ( .filename )
472 2 ▶ return $_[0] =~ /[^\/]\.([^\.\/]+)$/ ? $1 : undef;
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ m[[^/]\.([^\./]+)$] ? : 1 1 2
473 }
474  
475 ##############################################################################
476  
477 sub file_lock
478 2 ▶{
Subroutine file_lock: called CC=9 SCAR=24.6
Pod undocumented
479 2 my $fnh = shift; # file name or file handle
480 2 my $nb = shift; # non-blocking
481 2 my $ex = shift; # true if exclusive lock
482  
483 2 my $fh;
484 2 ▶ if( ref $fnh )
Branch: 1 branch
BranchTrueFalseTotal
if (ref $fnh) { } 0 2 2
485 {
486 # file handle
487 0 $fh = $fnh;
488 }
489 else
490 {
491 # filename
492 2 ▶ open( $fh, ( -e $fnh ? ( $ex ? '+<' : '<' ) : ( $ex ? '+>' : '>' ) ), $fnh ) or return undef;
Branch: 4 branches
BranchTrueFalseTotal
open $fh, -e $fnh ? $ex ? "+<" : "<" : ($ex ? "+>" : ">"), $fnh or return undef 2 0 2
-e $fnh ? : 2 0 2
$ex ? : 1 1 2
$ex ? : 0 0 0
493 }
494  
495 2 ▶ my $res = flock( $fh, ( $ex ? LOCK_EX : LOCK_SH ) | ( $nb ? LOCK_NB : 0 ) );
Branch: 2 branches
BranchTrueFalseTotal
$ex ? : 1 1 2
$nb ? : 2 0 2
496 2 ▶ return $res ? $fh : undef;
Branch: 1 branch
BranchTrueFalseTotal
$res ? : 2 0 2
497 }
498  
499 sub file_lock_nb
500 1 ▶{
Subroutine file_lock_nb: called CC=1 SCAR=0.0
Pod undocumented
501 1 return file_lock( shift(), 1 );
502 }
503  
504 sub file_lock_ex
505 0 ▶{
Subroutine file_lock_ex: not called CC=1 SCAR=6.9
Pod undocumented
506 0 return file_lock( shift(), shift(), 1 );
507 }
508  
509 sub file_lock_ex_nb
510 1 ▶{
Subroutine file_lock_ex_nb: called CC=1 SCAR=0.0
Pod undocumented
511 1 return file_lock( shift(), 1, 1 );
512 }
513  
514 # needs first arg to be file handle returned from any file_lock* function above
515 sub file_unlock
516 2 ▶{
Subroutine file_unlock: called CC=1 SCAR=0.0
Pod undocumented
517 2 return flock( shift(), LOCK_UN );
518 }
519  
520 ##############################################################################
521  
522 sub dir_path_make
523 4 ▶{
Subroutine dir_path_make: called CC=5 SCAR=16.3
Pod undocumented
524 4 my $path = shift;
525 4 my %opt = @_;
526  
527 4 ▶ my $mask = $opt{ 'MASK' } || oct('700');
Condition50%1/2
$opt{'MASK'} || 448
l!l
04
MC/DC0%0/1
$opt{'MASK'} || 448
$opt{'MASK'}
Truth table50%1/2
A
A= $opt{'MASK'}
Aresult
11
00
528  
529 4 my $abs;
530  
531 4 $path =~ s/\/+$/\//o;
532 4 ▶ $abs = '/' if $path =~ s/^\/+//o;
Branch: 1 branch
BranchTrueFalseTotal
if $path =~ s[^/+][]o 4 0 4
533  
534 4 my @path = split /\/+/, $path;
535  
536 4 $path = $abs;
537 4 for my $p ( @path )
538 {
539 18 $path .= "$p/";
540 18 mkdir( $path, $mask ); # should check if EEXISTS but still the same outcome
541 18 ▶ return 0 unless -d $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $path 0 18 18
542 }
543 4 return 1;
544 }
545  
546 sub dir_path_ensure
547 2 ▶{
Subroutine dir_path_ensure: called CC=3 SCAR=11.0
Pod undocumented
548 2 my $dir = shift;
549  
550 2 ▶ dir_path_make( $dir, @_ ) unless -d $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 1 1 2
551 2 ▶ return undef unless -d $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 0 2 2
552 2 return $dir;
553 }
554  
555 ##############################################################################
556  
557 3 my %SLASH_ESCAPES = ( "\\" => '\\\\', "\n" => '\\n', "\r" => '\\r', "\t" => '\\t', "=" => '\\=', ":" => '\\:', );
558 3 my %SLASH_ESCAPES_REV = reverse %SLASH_ESCAPES;
559  
560 sub str_escape_ipl
561 14 ▶{
Subroutine str_escape_ipl: called CC=1 SCAR=0.0
Pod undocumented
562 14 $_[0] =~ s/[\\\n\r\t=:]/$SLASH_ESCAPES{$&}/ge;
563 }
564  
565 sub str_unescape_ipl
566 11 ▶{
Subroutine str_unescape_ipl: called CC=1 SCAR=0.0
Pod undocumented
567 11 $_[0] =~ s/\\[\\nrt=:]/$SLASH_ESCAPES_REV{$&}/ge;
568 }
569  
570 sub str_escape
571 2 ▶{
Subroutine str_escape: called CC=1 SCAR=0.0
Pod undocumented
572 2 my $text = shift;
573  
574 2 str_escape_ipl( $text );
575 2 return $text;
576 }
577  
578 sub str_unescape
579 1 ▶{
Subroutine str_unescape: called CC=1 SCAR=0.0
Pod undocumented
580 1 my $text = shift;
581  
582 1 str_unescape_ipl( $text );
583 1 return $text;
584 }
585  
586 ##############################################################################
587 # url-style escape & hex escape
588 ##############################################################################
589  
590 3 our $URL_ESCAPES_DONE;
591 3 our %URL_ESCAPES;
592  
593 sub __url_escapes_init
594 6 ▶{
Subroutine __url_escapes_init: called CC=3 SCAR=11.0
595 6 ▶ return if $URL_ESCAPES_DONE;
Branch: 1 branch
BranchTrueFalseTotal
if $Data::Tools::URL_ESCAPES_DONE 3 3 6
596 3 for ( 0 .. 255 ) { $URL_ESCAPES{ chr( $_ ) } = sprintf("%%%02X", $_); }
597 3 $URL_ESCAPES_DONE = 1;
598 }
599  
600 # url (RFC 3986) is ascii only, anything else is UTF-8 bytes as %xx escapes:
601 # str_url_escape() takes characters (or UTF-8 bytes) and returns ascii url,
602 # str_url_unescape() takes url (ascii or UTF-8 bytes) and returns characters,
603 # so str_url_unescape( str_url_escape( $s ) ) eq $s
604  
605 sub str_url_escape
606 11 ▶{
Subroutine str_url_escape: called CC=2 SCAR=6.9
Pod undocumented
607 11 my $bytes = shift;
608  
609 # characters (perl utf8 string) become UTF-8 bytes, bytes stay as they are
610 11 ▶ $bytes = encode( 'UTF-8', $bytes ) if utf8::is_utf8( $bytes );
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($bytes) 2 9 11
611  
612 11 $bytes =~ s/([^A-Za-z_0-9])/$URL_ESCAPES{$1}/gs; # strict
613  
614 11 return $bytes;
615 }
616  
617 sub str_url_unescape
618 16 ▶{
Subroutine str_url_unescape: called CC=2 SCAR=6.9
Pod undocumented
619 16 my $text = shift;
620  
621 # guard: url is bytes, characters (perl utf8 string, possibly above 255)
622 # become UTF-8 bytes first, %xx escapes and ascii stay as they are
623 16 ▶ $text = encode( 'UTF-8', $text ) if utf8::is_utf8( $text );
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($text) 2 14 16
624  
625 16 $text =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/ge;
626  
627 16 $text = decode( 'UTF-8', $text ); # UTF-8 bytes to characters, an invalid byte becomes U+FFFD
628  
629 16 return $text;
630 }
631  
632  
633 # & &amp; &#38; &#x26;
634 # < &lt; &#60; &#x3C;
635 # > &gt; &#62; &#x3E;
636 # ' &apos; &#39; &#x27;
637 # " &quot; &#34; &#x22;
638  
639 3 my %HTML_ESCAPES = (
640 "&" => '&#38;',
641 '<' => '&#60;',
642 '>' => '&#62;',
643 "'" => '&#39;',
644 '"' => '&#34;',
645 '=' => '&#61;',
646 "`" => '&#96;',
647 '\\' => '&#92;',
648 );
649  
650 3 my %HTML_ESCAPES_TEXT = (
651 "&" => '&#38;',
652 '<' => '&#60;',
653 '>' => '&#62;',
654 );
655  
656 3 my %HTML_ESCAPES_ATTR = (
657 "&" => '&#38;',
658 '<' => '&#60;',
659 '>' => '&#62;',
660 "'" => '&#39;',
661 '"' => '&#34;',
662 );
663 3 my $HTML_ESCAPES_CHARS = join '', keys %HTML_ESCAPES;
664 3 my $HTML_ESCAPES_TEXT_CHARS = join '', keys %HTML_ESCAPES_TEXT;
665 3 my $HTML_ESCAPES_ATTR_CHARS = join '', keys %HTML_ESCAPES_ATTR;
666  
667 sub str_html_escape
668 1 ▶{
Subroutine str_html_escape: called CC=1 SCAR=0.0
Pod undocumented
669 1 my $text = shift;
670  
671 1 $text =~ s/([\Q$HTML_ESCAPES_CHARS\E])/$HTML_ESCAPES{ $1 }/go;
672  
673 1 return $text;
674 }
675  
676 sub str_html_escape_text
677 2 ▶{
Subroutine str_html_escape_text: called CC=1 SCAR=0.0
Pod undocumented
678 2 my $text = shift;
679  
680 2 $text =~ s/([\Q$HTML_ESCAPES_TEXT_CHARS\E])/$HTML_ESCAPES_TEXT{ $1 }/go;
681  
682 2 return $text;
683 }
684  
685 sub str_html_escape_attr
686 1 ▶{
Subroutine str_html_escape_attr: called CC=1 SCAR=0.0
Pod undocumented
687 1 my $text = shift;
688  
689 1 $text =~ s/([\Q$HTML_ESCAPES_ATTR_CHARS\E])/$HTML_ESCAPES_ATTR{ $1 }/go;
690  
691 1 return $text;
692 }
693  
694  
695 # named character references recognised by str_html_unescape().
696 # per WHATWG HTML Living Standard § 13.5 "Named character references"
697 # https://html.spec.whatwg.org/multipage/named-characters.html
698 # matching is case-sensitive and exact-string: the table is a flat list
699 # of reference names (including their exact casing), mapped to code points.
700 # it is intentional that many code points have multiple names (e.g. both
701 # amp and AMP point to U+0026, but they are separate table entries).
702 # a trailing ';' is always required. this set is the legacy no-semicolon-
703 # required WHATWG subset (where the semicolon is optional per HTML 2.0 for
704 # certain names, but we enforce it here for simplicity)
705 # https://github.com/whatwg/html-build/blob/main/entities/json-entities-legacy.inc
706 # plus 'apos', which is semicolon-required and outside that table, but
707 # universally expected.
708 3 my %HTML_NAMED_ENTITIES = (
709 AElig => chr(198), AMP => chr(38), Aacute => chr(193), Acirc => chr(194),
710 Agrave => chr(192), Aring => chr(197), Atilde => chr(195), Auml => chr(196),
711 COPY => chr(169), Ccedil => chr(199), ETH => chr(208), Eacute => chr(201),
712 Ecirc => chr(202), Egrave => chr(200), Euml => chr(203), GT => chr(62),
713 Iacute => chr(205), Icirc => chr(206), Igrave => chr(204), Iuml => chr(207),
714 LT => chr(60), Ntilde => chr(209), Oacute => chr(211), Ocirc => chr(212),
715 Ograve => chr(210), Oslash => chr(216), Otilde => chr(213), Ouml => chr(214),
716 QUOT => chr(34), REG => chr(174), THORN => chr(222), Uacute => chr(218),
717 Ucirc => chr(219), Ugrave => chr(217), Uuml => chr(220), Yacute => chr(221),
718 aacute => chr(225), acirc => chr(226), acute => chr(180), aelig => chr(230),
719 agrave => chr(224), amp => chr(38), apos => chr(39), aring => chr(229),
720 atilde => chr(227), auml => chr(228), brvbar => chr(166), ccedil => chr(231),
721 cedil => chr(184), cent => chr(162), copy => chr(169), curren => chr(164),
722 deg => chr(176), divide => chr(247), eacute => chr(233), ecirc => chr(234),
723 egrave => chr(232), eth => chr(240), euml => chr(235), frac12 => chr(189),
724 frac14 => chr(188), frac34 => chr(190), gt => chr(62), iacute => chr(237),
725 icirc => chr(238), iexcl => chr(161), igrave => chr(236), iquest => chr(191),
726 iuml => chr(239), laquo => chr(171), lt => chr(60), macr => chr(175),
727 micro => chr(181), middot => chr(183), nbsp => chr(160), not => chr(172),
728 ntilde => chr(241), oacute => chr(243), ocirc => chr(244), ograve => chr(242),
729 ordf => chr(170), ordm => chr(186), oslash => chr(248), otilde => chr(245),
730 ouml => chr(246), para => chr(182), plusmn => chr(177), pound => chr(163),
731 quot => chr(34), raquo => chr(187), reg => chr(174), sect => chr(167),
732 shy => chr(173), sup1 => chr(185), sup2 => chr(178), sup3 => chr(179),
733 szlig => chr(223), thorn => chr(254), times => chr(215), uacute => chr(250),
734 ucirc => chr(251), ugrave => chr(249), uml => chr(168), uuml => chr(252),
735 yacute => chr(253), yen => chr(165), yuml => chr(255),
736 );
737  
738 sub _html_unescape_codepoint
739 6 ▶{
Subroutine _html_unescape_codepoint: called CC=5 SCAR=17.2
740 6 my $n = shift;
741 6 ▶ return undef if $n <= 0 || $n > 0x10FFFF || ( $n >= 0xD800 && $n <= 0xDFFF );
Branch: 1 branch
BranchTrueFalseTotal
if $n <= 0 or $n > 1114111 or $n >= 55296 and $n <= 57343 1 5 6
Condition55%5/9
$n <= 0 or $n > 1114111 or $n >= 55296 and $n <= 57343
l!l&&r!l&&!r
105
$n <= 0 or $n > 1114111
l!l&&r!l&&!r
105
$n >= 55296 and $n <= 57343
!ll&&!rl&&r
500
MC/DC25%1/4
$n <= 0 or $n > 1114111 or $n >= 55296 and $n <= 57343
$n <= 0 $n > 1114111 $n >= 55296 $n <= 57343
Truth table40%2/5
A or B or C and D
A= $n <= 0B= $n > 1114111C= $n >= 55296D= $n <= 57343
ABCDresult
1XXX1
01XX1
00111
000X0
00100
742 5 return chr( $n );
743 }
744  
745 3 my $HTML_UNESCAPE_RE = qr//;
746 sub str_html_unescape
747 5 ▶{
Subroutine str_html_unescape: called CC=7 SCAR=20.7
Pod undocumented
748 5 my $text = shift;
749 5 $text =~ s{(&(?:\#[xX]([0-9A-Fa-f]+)|\#(\d+)|([A-Za-z][A-Za-z0-9]*));)}
750 {
751 defined $2 ? ( _html_unescape_codepoint( hex( $2 ) ) // $1 )
752 : defined $3 ? ( _html_unescape_codepoint( $3 ) // $1 )
753 10 ▶ : defined $4 ? ( $HTML_NAMED_ENTITIES{ $4 } // $1 )
Branch: 3 branches
BranchTrueFalseTotal
defined $2 ? : 1 9 10
defined $3 ? : 5 4 9
defined $4 ? : 4 0 4
Condition55%5/9
_html_unescape_codepoint(hex $2) // $1
l!l&&r!l&&!r
100
_html_unescape_codepoint($3) // $1
l!l&&r!l&&!r
401
$HTML_NAMED_ENTITIES{$4} // $1
l!l&&r!l&&!r
301
MC/DC0%0/2
_html_unescape_codepoint(hex $2) // $1
_html_unescape_codepoint(hex $2) $1
MC/DC50%1/2
_html_unescape_codepoint($3) // $1
_html_unescape_codepoint($3) $1
MC/DC50%1/2
$HTML_NAMED_ENTITIES{$4} // $1
$HTML_NAMED_ENTITIES{$4} $1
Truth table33%1/3
A // B
A= _html_unescape_codepoint(hex $2)B= $1
ABresult
1X1
011
000
Truth table66%2/3
A // B
A= _html_unescape_codepoint($3)B= $1
ABresult
1X1
011
000
Truth table66%2/3
A // B
A= $HTML_NAMED_ENTITIES{$4}B= $1
ABresult
1X1
011
000
754 : $1
755 }gexo;
756 5 return $text;
757 }
758  
759 ##############################################################################
760  
761 sub str_hex
762 3 ▶{
Subroutine str_hex: called CC=1 SCAR=0.0
Pod undocumented
763 3 return unpack( "H*", $_[0] );
764 }
765  
766 sub str_unhex
767 2 ▶{
Subroutine str_unhex: called CC=1 SCAR=0.0
Pod undocumented
768 2 return pack( "H*", $_[0] );
769 }
770  
771 sub str_hex_utf8
772 11 ▶{
Subroutine str_hex_utf8: called CC=1 SCAR=0.0
Pod undocumented
773 11 return unpack( "H*", encode( 'UTF-8', $_[0] ) );
774 }
775  
776 sub str_unhex_utf8
777 9 ▶{
Subroutine str_unhex_utf8: called CC=1 SCAR=0.0
Pod undocumented
778 9 return decode( 'UTF-8', pack( "H*", $_[0] ) );
779 }
780  
781 ##############################################################################
782  
783 sub str_num_comma
784 2 ▶{
Subroutine str_num_comma: called CC=2 SCAR=6.9
Pod undocumented
785 2 my $data = shift;
786 2 ▶ my $pad = shift || '`';
Condition100%2/2
shift() || '`'
l!l
11
MC/DC100%1/1
shift() || '`'
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
787 2 $data = reverse $data;
788 2 $data =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1$pad/g;
789 2 $data = reverse $data;
790 2 return $data;
791 }
792  
793 sub str_pad
794 18 ▶{
Subroutine str_pad: called CC=4 SCAR=13.9
Pod undocumented
795 18 my $str = shift;
796 18 my $len = shift;
797 18 my $pad = shift;
798 18 ▶ $pad = ' ' unless defined $pad;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pad 17 1 18
799  
800 18 ▶ $str = reverse $str if $len < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $len < 0 7 11 18
801 18 $str = substr( $str . ($pad x abs($len)), 0, abs($len) );
802 18 ▶ $str = reverse $str if $len < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $len < 0 7 11 18
803  
804 18 return $str;
805 }
806  
807 sub str_pad_center
808 3 ▶{
Subroutine str_pad_center: called CC=3 SCAR=11.1
Pod undocumented
809 3 my $str = shift;
810 3 my $len = shift;
811 3 my $pad = shift;
812 3 ▶ $pad = ' ' unless defined $pad;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pad 3 0 3
813  
814 3 my $padlen = int((abs($len) - length($str))/2);
815 3 ▶ my $padding = $pad x $padlen if $padlen > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $padlen > 0 3 0 3
816  
817 3 $str = substr( $padding . $str . $padding . $pad, 0, abs($len) );
818  
819 3 return $str;
820 }
821  
822 sub str_countable
823 27 ▶{
Subroutine str_countable: called CC=3 SCAR=11.0
Pod undocumented
824 27 my $count = shift;
825 27 my $one = shift;
826 27 my $many = shift;
827  
828 27 ▶ return $count == 0 ? $many : $count == 1 ? $one : $many;
Branch: 2 branches
BranchTrueFalseTotal
$count == 0 ? : 8 19 27
$count == 1 ? : 11 8 19
829 }
830  
831 sub str_kmg_to_num
832 4 ▶{
Subroutine str_kmg_to_num: called CC=3 SCAR=11.0
Pod undocumented
833 4 my $s = uc shift;
834 4 ▶ return undef unless $s =~ /^\s*(\d+(\.\d*)?)(\s*([KMGTP]))?/;
Branch: 1 branch
BranchTrueFalseTotal
unless $s =~ /^\s*(\d+(\.\d*)?)(\s*([KMGTP]))?/ 1 3 4
835 3 ▶ return $1 unless $4;
Branch: 1 branch
BranchTrueFalseTotal
unless $4 1 2 3
836 2 return $1 * ( 1024 ** ( index( 'KMGTP', $4 ) + 1 ) );
837 }
838  
839 sub str_hms_to_secs
840 3 ▶{
Subroutine str_hms_to_secs: called CC=8 SCAR=20.9
Pod undocumented
841 3 my $s = uc shift;
842  
843 3 my $secs;
844 3 ▶ $s .= 's' if $s =~ /^[\s\d]+$/;
Branch: 1 branch
BranchTrueFalseTotal
if $s =~ /^[\s\d]+$/ 1 2 3
845 3 ▶ while( $s =~ /(\d+)\s*([WDHMS])/gi )
Branch: 1 branch
BranchTrueFalseTotal
if ($s =~ /(\d+)\s*([WDHMS])/gi) 4 3 7
846 {
847 4 ▶ if ( lc $2 eq 's' ) { $secs += $1; }
Branch: 5 branches
BranchTrueFalseTotal
if (lc $2 eq 's') { } 1 3 4
elsif (lc $2 eq 'm') { } 1 2 3
elsif (lc $2 eq 'h') { } 1 1 2
elsif (lc $2 eq 'd') { } 0 1 1
elsif (lc $2 eq 'w') { } 1 0 1
848 1 elsif( lc $2 eq 'm' ) { $secs += $1 * 60; }
849 1 elsif( lc $2 eq 'h' ) { $secs += $1 * 60 * 60; }
850 0 elsif( lc $2 eq 'd' ) { $secs += $1 * 60 * 60 * 24; }
851 1 elsif( lc $2 eq 'w' ) { $secs += $1 * 60 * 60 * 24 * 7; }
852 }
853  
854 3 return $secs;
855 }
856  
857 ##############################################################################
858 # str_password_strength()
859 # returns a number representing password strength
860 # it is tuned to give password strength in a number close to percents:
861 # less than 50 weak, 50-75 good, 76-100 strong, more than 100 very strong
862  
863 sub str_password_strength
864 2 ▶{
Subroutine str_password_strength: called CC=4 SCAR=13.9
Pod undocumented
865 2 my $p = shift;
866  
867 2 $p =~ s/(.)\1+/$1/g; # reduce repeating chars
868  
869 2 my $l = length( $p ); # remaining string length
870  
871 2 ▶ return 0 unless $l > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $l > 0 0 2 2
872  
873 2 my $lc = $p =~ tr/a-z/a-z/; # lower case letters
874 2 my $uc = $p =~ tr/A-Z/A-Z/; # upper case letters
875 2 my $dc = $p =~ tr/0-9/0-9/; # digits
876 2 my $sc = $l - $lc - $uc - $dc; # special chars
877  
878 2 my $cc = ( $lc > 0 ) + ( $uc > 0 ) + ( $dc > 0 ) + ( $sc > 0 ) ; # used classes count
879 2 my $as = ( $lc > 0 ) * 26 + ( $uc > 0 ) * 26 + ( $dc > 0 ) * 10 + ( $sc > 0 ) * 30; # alphabet size
880  
881 2 ▶ return 0 unless $cc > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $cc > 0 0 2 2
882  
883 2 ▶ my $cp = $cc < 2 ? 2 : 1; # class count penalty
Branch: 1 branch
BranchTrueFalseTotal
$cc < 2 ? : 1 1 2
884 2 my $res = $l * log( $as ) / $cp;
885  
886 # print "<$p> l=$l lc=$lc uc=$uc dc=$dc sc=$sc cc=$cc as=$as nb=$nb ($res)\n";
887  
888 2 return $res;
889 }
890  
891 ##############################################################################
892 # MISC string utils
893  
894 # takes one SCALAR, returns first letter in upper case and lower case the rest
895 sub str_capitalize
896 1 ▶{
Subroutine str_capitalize: called CC=1 SCAR=0.0
Pod undocumented
897 1 return uc( substr( $_[0], 0, 1 ) ) . lc( substr( $_[0], 1 ) );
898 }
899  
900 # returns concatenated first letters of all words in the string
901 # "James Webb Telescope" will return JWT
902 sub str_initials
903 1 ▶{
Subroutine str_initials: called CC=1 SCAR=0.0
Pod undocumented
904 1 return join '', $_[0] =~ /(\S)\S*/g;
905 }
906  
907 ##############################################################################
908  
909 sub hash2str
910 2 ▶{
Subroutine hash2str: called CC=2 SCAR=6.9
Pod undocumented
911 2 my $hr = shift;
912  
913 2 my $str;
914 2 for my $k ( keys %$hr )
915 {
916 4 my $v = $hr->{ $k };
917 4 str_escape_ipl( $k );
918 4 str_escape_ipl( $v );
919 4 $str .= "$k=$v\n";
920 }
921  
922 2 return $str;
923 }
924  
925 sub str2hash
926 3 ▶{
Subroutine str2hash: called CC=2 SCAR=6.9
Pod undocumented
927 3 my $str = shift;
928 3 my %hr;
929  
930 3 for( split /\n/, $str )
931 {
932 5 my ( $k, $v ) = split /(?<!\\)=/, $_, 2;
933 5 str_unescape_ipl( $k );
934 5 str_unescape_ipl( $v );
935 5 $hr{ $k } = $v;
936 }
937  
938 3 return \%hr;
939 }
940  
941 sub hash2str_keys
942 2 ▶{
Subroutine hash2str_keys: called CC=2 SCAR=6.9
Pod undocumented
943 2 my $hr = shift;
944  
945 2 my $str;
946 2 for my $key ( @_ )
947 {
948 2 my $k = $key; # do not modify caller's data, @_ elements are aliases
949 2 my $v = $hr->{ $k };
950 2 str_escape_ipl( $k );
951 2 str_escape_ipl( $v );
952 2 $str .= "$k=$v\n";
953 }
954  
955 2 return $str;
956 }
957  
958  
959 sub str2hash_url
960 2 ▶{
Subroutine str2hash_url: called CC=3 SCAR=11.1
Pod undocumented
961 2 my $str = shift;
962  
963 2 my %h;
964 2 for( split( /\n/, $str ) )
965 {
966 3 ▶ $h{ str_url_unescape( $1 ) } = str_url_unescape( $2 ) if ( /^([^=]+)=(.*)$/ );
Branch: 1 branch
BranchTrueFalseTotal
if /^([^=]+)=(.*)$/ 3 0 3
967 }
968 2 return \%h;
969 }
970  
971 sub hash2str_url
972 2 ▶{
Subroutine hash2str_url: called CC=2 SCAR=6.9
Pod undocumented
973 2 my $hr = shift; # hash reference
974  
975 2 my $s = "";
976 2 for my $k ( keys %$hr )
977 {
978 3 my $v = $hr->{ $k };
979 3 $k = str_url_escape( $k );
980 3 $v = str_url_escape( $v );
981 3 $s .= "$k=$v\n";
982 }
983 2 return $s;
984 }
985  
986 sub url2hash
987 1 ▶{
Subroutine url2hash: called CC=3 SCAR=11.1
Pod undocumented
988 1 my $str = shift;
989 1 my %hash;
990 1 for( split( /&/, $str ) )
991 {
992 2 ▶ $hash{ uc str_url_unescape( $1 ) } = str_url_unescape( $2 ) if ( /^([^=]+)=(.*)$/ );
Branch: 1 branch
BranchTrueFalseTotal
if /^([^=]+)=(.*)$/ 2 0 2
993 }
994 1 return \%hash;
995 }
996  
997 # FIXME: hash2json(), json2hash(), hash_load_json() and hash_save_json() now
998 # return undef on failure where they used to die, and hash_save_json_pp()
999 # now writes canonical UTF-8; exported by default, needs a Changes entry
1000 sub hash2json
1001 2 ▶{
Subroutine hash2json: called CC=1 SCAR=0.0
Pod undocumented
1002 2 return scalar eval { encode_json( $_[0] ) };
1003 }
1004  
1005 3 my $__JSON_PP = JSON->new()->utf8()->canonical(1)->pretty( 1 );
1006 sub hash2json_pp
1007 3 ▶{
Subroutine hash2json_pp: called CC=1 SCAR=0.0
Pod undocumented
1008 3 return scalar eval { $__JSON_PP->encode( $_[0] ) };
1009 }
1010  
1011 # CanoniCal :)
1012 3 my $__JSON_CC = JSON->new()->utf8()->canonical(1);
1013 sub hash2json_cc
1014 0 ▶{
Subroutine hash2json_cc: not called CC=1 SCAR=6.9
Pod undocumented
1015 0 return scalar eval { $__JSON_CC->encode( $_[0] ) };
1016 }
1017  
1018 sub json2hash
1019 4 ▶{
Subroutine json2hash: called CC=1 SCAR=0.0
Pod undocumented
1020 4 return scalar eval { decode_json( $_[0] ); };
1021 }
1022  
1023 ##############################################################################
1024  
1025 sub __hash_ulc
1026 12 ▶{
Subroutine __hash_ulc: called CC=6 SCAR=17.9
1027 12 my $hr = shift;
1028 12 my $uc = shift;
1029 12 my $ipl = shift;
1030  
1031 12 ▶ my $nr = $ipl ? $hr : {};
Branch: 1 branch
BranchTrueFalseTotal
$ipl ? : 10 2 12
1032 12 for my $k ( keys %$hr )
1033 {
1034 10 my $v = $hr->{ $k };
1035 10 my $old_k = $k;
1036 10 ▶ $k = $uc ? uc( $k ) : lc( $k );
Branch: 1 branch
BranchTrueFalseTotal
$uc ? : 7 3 10
1037 10 $nr->{ $k } = $v;
1038 10 ▶ delete $nr->{ $old_k } if ($ipl and $k ne $old_k);
Branch: 1 branch
BranchTrueFalseTotal
if $ipl and $k ne $old_k 2 8 10
Condition100%3/3
$ipl and $k ne $old_k
!ll&&!rl&&r
442
MC/DC100%2/2
$ipl and $k ne $old_k
$ipl $k ne $old_k
Truth table100%3/3
A and B
A= $iplB= $k ne $old_k
ABresult
0X0
100
111
1039 }
1040 12 return $nr;
1041 }
1042  
1043 sub hash_uc
1044 1 ▶{
Subroutine hash_uc: called CC=1 SCAR=0.0
Pod undocumented
1045 1 return __hash_ulc( shift(), 1, 0 );
1046 }
1047  
1048 sub hash_lc
1049 1 ▶{
Subroutine hash_lc: called CC=1 SCAR=0.0
Pod undocumented
1050 1 return __hash_ulc( shift(), 0, 0 );
1051 }
1052  
1053 sub hash_uc_ipl
1054 9 ▶{
Subroutine hash_uc_ipl: called CC=1 SCAR=0.0
Pod undocumented
1055 9 return __hash_ulc( shift(), 1, 1 );
1056 }
1057  
1058 sub hash_lc_ipl
1059 1 ▶{
Subroutine hash_lc_ipl: called CC=1 SCAR=0.0
Pod undocumented
1060 1 return __hash_ulc( shift(), 0, 1 );
1061 }
1062  
1063 ##############################################################################
1064  
1065 sub hash_save
1066 1 ▶{
Subroutine hash_save: called CC=2 SCAR=6.9
Pod undocumented
1067 1 my $fn = shift;
1068 # @_ array of hash references
1069 1 my $data;
1070 1 $data .= hash2str( $_ ) for @_;
1071 1 return file_text_save( $fn, $data );
1072 }
1073  
1074 sub hash_load
1075 2 ▶{
Subroutine hash_load: called CC=1 SCAR=0.0
Pod undocumented
1076 2 my $fn = shift;
1077  
1078 2 return str2hash( file_text_load( $fn ) );
1079 }
1080  
1081 sub hash_save_keys
1082 1 ▶{
Subroutine hash_save_keys: called CC=1 SCAR=0.0
Pod undocumented
1083 1 my $fn = shift;
1084 1 my $hr = shift;
1085  
1086 1 my $data;
1087 1 $data .= hash2str_keys( $hr, @_ );
1088 1 return file_save( $fn, $data );
1089 }
1090  
1091 sub hash_save_url
1092 1 ▶{
Subroutine hash_save_url: called CC=2 SCAR=6.9
Pod undocumented
1093 1 my $fn = shift;
1094 # @_ array of hash references
1095 1 my $data;
1096 1 $data .= hash2str_url( $_ ) for @_;
1097 1 return file_save( $fn, $data );
1098 }
1099  
1100 sub hash_load_url
1101 1 ▶{
Subroutine hash_load_url: called CC=1 SCAR=0.0
Pod undocumented
1102 1 my $fn = shift;
1103  
1104 1 return str2hash_url( file_load( $fn ) );
1105 }
1106  
1107 sub hash_save_json
1108 1 ▶{
Subroutine hash_save_json: called CC=2 SCAR=7.1
Pod undocumented
1109 1 my $fn = shift;
1110 1 my $hr = shift;
1111  
1112 1 ▶ return file_save( $fn, hash2json( $hr ) // return undef );
Condition50%1/2
hash2json($hr) // (return undef)
l!l
10
MC/DC0%0/1
hash2json($hr) // (return undef)
hash2json($hr)
Truth table50%1/2
A
A= hash2json($hr)
Aresult
11
00
1113 }
1114  
1115 sub hash_save_json_pp
1116 1 ▶{
Subroutine hash_save_json_pp: called CC=2 SCAR=7.1
Pod undocumented
1117 1 my $fn = shift;
1118 1 my $hr = shift;
1119  
1120 1 ▶ return file_save( $fn, hash2json_pp( $hr ) // return undef );
Condition50%1/2
hash2json_pp($hr) // (return undef)
l!l
10
MC/DC0%0/1
hash2json_pp($hr) // (return undef)
hash2json_pp($hr)
Truth table50%1/2
A
A= hash2json_pp($hr)
Aresult
11
00
1121 }
1122  
1123 sub hash_load_json
1124 2 ▶{
Subroutine hash_load_json: called CC=1 SCAR=0.0
Pod undocumented
1125 2 my $fn = shift;
1126  
1127 2 return json2hash( file_load( $fn ) );
1128 }
1129  
1130 ##############################################################################
1131  
1132 sub hash_fingerprint
1133 0 ▶{
Subroutine hash_fingerprint: not called CC=4 SCAR=30.0
Pod undocumented
1134 0 ▶ return undef if ! defined $_[0] or ref( $_[0] ) ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $_[0] or ref $_[0] ne "HASH" 0 0 0
Condition0%0/3
not defined $_[0] or ref $_[0] ne "HASH"
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $_[0] or ref $_[0] ne "HASH"
not defined $_[0] ref $_[0] ne "HASH"
Truth table0%0/3
not(A) or B
A= not defined $_[0]B= ref $_[0] ne "HASH"
ABresult
1X1
011
000
1135 0 ▶ return sha1_hex( hash2json_cc( $_[0] ) // return undef );
Condition0%0/2
hash2json_cc($_[0]) // (return undef)
l!l
00
MC/DC0%0/1
hash2json_cc($_[0]) // (return undef)
hash2json_cc($_[0])
Truth table0%0/2
A
A= hash2json_cc($_[0])
Aresult
11
00
1136 }
1137  
1138 sub hash_validate
1139 14 ▶{
Subroutine hash_validate: called CC=23 SCAR=31.4
Pod documented
1140 14 my $hr = shift; # hashref to validate
1141 14 my $vr = shift; # hashref with expectations
1142  
1143 14 my @err; # invalid keys
1144 14 for my $k ( keys %$hr )
1145 {
1146 15 my $v = $hr->{ $k };
1147 15 ▶ if( ! exists $vr->{ $k } )
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $vr->{$k}) 1 14 15
1148 {
1149 1 push @err, $k;
1150 1 next;
1151 }
1152  
1153 14 my $vv = $vr->{ $k };
1154  
1155 14 ▶ if( ref( $v ) eq 'HASH' )
Branch: 5 branches
BranchTrueFalseTotal
if (ref $v eq 'HASH') { } 1 13 14
elsif ($vv =~ /^\s*(int|real|float)\s*(\(\s*(\d+)\s*,\s*(\d+)\s*\))?\s*$/i) { } 7 6 13
elsif ($vv =~ /^\s*RE(I)?:\s*(.*?)\s*$/i) { } 3 3 6
elsif ($vv =~ /^\s*(-d|dir|directory)\s*$/i) { } 1 2 3
elsif ($vv =~ /^\s*(-f|file)\s*$/i) { } 2 0 2
1156 {
1157 1 my @e = hash_validate( $v, $vv );
1158 1 for my $e ( @e )
1159 {
1160 1 push @err, "$k/$e";
1161 }
1162 }
1163 elsif( $vv =~ /^\s*(int|real|float)\s*(\(\s*(\d+)\s*,\s*(\d+)\s*\))?\s*$/i )
1164 {
1165 7 my $y = uc $1;
1166 7 my $f = $3;
1167 7 my $t = $4;
1168  
1169 7 $v =~ s/[\s'`]+//g;
1170  
1171 7 my $re;
1172 7 ▶ $re = qr/^[-+]?\d+$/ if $y eq 'INT';
Branch: 1 branch
BranchTrueFalseTotal
if $y eq "INT" 6 1 7
1173 7 ▶ $re = qr/^[-+]?\d+(\.\d*)?$/ if $y eq 'REAL' or $y eq 'FLOAT';
Branch: 1 branch
BranchTrueFalseTotal
if $y eq "REAL" or $y eq "FLOAT" 1 6 7
Condition66%2/3
$y eq "REAL" or $y eq "FLOAT"
l!l&&r!l&&!r
106
MC/DC50%1/2
$y eq "REAL" or $y eq "FLOAT"
$y eq "REAL" $y eq "FLOAT"
Truth table66%2/3
A or B
A= $y eq "REAL"B= $y eq "FLOAT"
ABresult
1X1
011
000
1174  
1175 #print STDERR Data::Dumper::Dumper( '=int=real='x5, $k, $v, $vv, $re );
1176  
1177 7 ▶ if( $v =~ /$re/ )
Branch: 1 branch
BranchTrueFalseTotal
if ($v =~ /$re/) { } 4 3 7
1178 {
1179 4 ▶ push @err, $k if $f ne '' and $v < $f;
Branch: 1 branch
BranchTrueFalseTotal
if $f ne "" and $v < $f 0 4 4
Condition66%2/3
$f ne "" and $v < $f
!ll&&!rl&&r
220
MC/DC0%0/2
$f ne "" and $v < $f
$f ne "" $v < $f
Truth table66%2/3
A and B
A= $f ne ""B= $v < $f
ABresult
0X0
100
111
1180 4 ▶ push @err, $k if $t ne '' and $v > $t;
Branch: 1 branch
BranchTrueFalseTotal
if $t ne "" and $v > $t 1 3 4
Condition100%3/3
$t ne "" and $v > $t
!ll&&!rl&&r
211
MC/DC100%2/2
$t ne "" and $v > $t
$t ne "" $v > $t
Truth table100%3/3
A and B
A= $t ne ""B= $v > $t
ABresult
0X0
100
111
1181 }
1182 else
1183 {
1184 3 push @err, $k;
1185 }
1186 }
1187 elsif( $vv =~ /^\s*RE(I)?:\s*(.*?)\s*$/i )
1188 {
1189 3 my $ic = $1; # ignore case
1190 3 ▶ my $re = $ic ? qr/$2/i : qr/$2/;
Branch: 1 branch
BranchTrueFalseTotal
$ic ? : 1 2 3
1191 # print Data::Dumper::Dumper( '=re=rei='x5, $k, $v, $vv, $re, $ic );
1192 3 ▶ push @err, $k unless $v =~ /$re/;
Branch: 1 branch
BranchTrueFalseTotal
unless $v =~ /$re/i 1 2 3
1193 }
1194 elsif( $vv =~ /^\s*(-d|dir|directory)\s*$/i )
1195 {
1196 1 ▶ push @err, $k unless -d $v;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $v 0 1 1
1197 }
1198 elsif( $vv =~ /^\s*(-f|file)\s*$/i )
1199 {
1200 2 ▶ push @err, $k unless -f $v;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $v 1 1 2
1201 }
1202 }
1203  
1204 14 ▶ return wantarray() ? sort( @err ) : @err > 0 ? 0 : 1;
Branch: 2 branches
BranchTrueFalseTotal
wantarray ? : 3 11 14
@err > 0 ? : 4 7 11
1205 }
1206  
1207 ##############################################################################
1208  
1209 # handle recursive hashes until perl 5.22 etc.
1210 sub hash_lock_recursive
1211 2 ▶{
Subroutine hash_lock_recursive: called CC=3 SCAR=11.0
Pod undocumented
1212 2 my $hr = shift;
1213  
1214 2 lock_hashref( $hr );
1215 2 for my $vr ( values %$hr )
1216 {
1217 3 ▶ next unless ref( $vr ) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $vr eq "HASH" 2 1 3
1218 1 hash_lock_recursive( $vr );
1219 }
1220  
1221 2 return $hr;
1222 }
1223  
1224 sub hash_unlock_recursive
1225 2 ▶{
Subroutine hash_unlock_recursive: called CC=3 SCAR=11.0
Pod undocumented
1226 2 my $hr = shift;
1227  
1228 2 unlock_hashref( $hr );
1229 2 for my $vr ( values %$hr )
1230 {
1231 3 ▶ next unless ref( $vr ) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $vr eq "HASH" 2 1 3
1232 1 hash_unlock_recursive( $vr );
1233 }
1234  
1235 2 return $hr;
1236 }
1237  
1238 sub hash_keys_lock_recursive
1239 2 ▶{
Subroutine hash_keys_lock_recursive: called CC=3 SCAR=11.0
Pod undocumented
1240 2 my $hr = shift;
1241  
1242 2 lock_ref_keys( $hr );
1243 2 for my $vr ( values %$hr )
1244 {
1245 3 ▶ next unless ref( $vr ) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $vr eq "HASH" 2 1 3
1246 1 hash_keys_lock_recursive( $vr );
1247 }
1248  
1249 2 return $hr;
1250 }
1251  
1252 sub hr_traverse_vals
1253 3 ▶{
Subroutine hr_traverse_vals: called CC=5 SCAR=16.2
Pod undocumented
1254 3 my $hr = shift;
1255 3 my $sub = shift;
1256  
1257 3 for( keys %$hr )
1258 {
1259 5 my $v = $hr->{ $_ };
1260 5 my $r = ref( $v );
1261 5 ▶ if( $r eq 'HASH' )
Branch: 3 branches
BranchTrueFalseTotal
if ($r eq 'HASH') { } 1 4 5
elsif ($r eq 'ARRAY') { } 1 3 4
elsif ($r eq '') { } 3 0 3
1262 {
1263 1 hr_traverse_vals( $v, $sub );
1264 }
1265 elsif( $r eq 'ARRAY' )
1266 {
1267 1 ar_traverse_vals( $v, $sub );
1268 }
1269 elsif( $r eq '' )
1270 {
1271 3 $hr->{ $_ } = $sub->( $v );
1272 }
1273 else
1274 {
1275 0 confess "unsupported VALUE TYPE";
1276 }
1277 }
1278 }
1279  
1280 sub ar_traverse_vals
1281 3 ▶{
Subroutine ar_traverse_vals: called CC=5 SCAR=16.2
Pod undocumented
1282 3 my $ar = shift;
1283 3 my $sub = shift;
1284  
1285 3 for( @$ar )
1286 {
1287 6 my $r = ref( $_ );
1288 6 ▶ if( $r eq 'HASH' )
Branch: 3 branches
BranchTrueFalseTotal
if ($r eq 'HASH') { } 1 5 6
elsif ($r eq 'ARRAY') { } 1 4 5
elsif ($r eq '') { } 4 0 4
1289 {
1290 1 hr_traverse_vals( $_, $sub );
1291 }
1292 elsif( $r eq 'ARRAY' )
1293 {
1294 1 ar_traverse_vals( $_, $sub );
1295 }
1296 elsif( $r eq '' )
1297 {
1298 4 $_ = $sub->( $_ );
1299 }
1300 else
1301 {
1302 0 confess "unsupported VALUE TYPE";
1303 }
1304 }
1305 }
1306  
1307 ##############################################################################
1308  
1309 sub list_uniq
1310 1 ▶{
Subroutine list_uniq: called CC=1 SCAR=0.0
Pod undocumented
1311 1 my %z;
1312 1 return grep ! $z{ $_ }++, @_;
1313 }
1314  
1315 ##############################################################################
1316  
1317 sub perl_package_to_file
1318 1 ▶{
Subroutine perl_package_to_file: called CC=1 SCAR=0.0
Pod undocumented
1319 1 my $s = shift;
1320 1 $s =~ s/::/\//g;
1321 1 $s .= '.pm';
1322 1 return $s;
1323 }
1324  
1325 ##############################################################################
1326  
1327 sub wp_hex
1328 2 ▶{
Subroutine wp_hex: called CC=1 SCAR=0.0
Pod undocumented
1329 2 my $s = shift;
1330  
1331 2 my $wp = Digest->new( 'Whirlpool' );
1332 2 $wp->add( $s );
1333 2 my $hex = $wp->hexdigest();
1334  
1335 2 return $hex;
1336 }
1337  
1338 sub md5_hex
1339 2 ▶{
Subroutine md5_hex: called CC=1 SCAR=0.0
Pod undocumented
1340 2 my $s = shift;
1341  
1342 2 my $hex = Digest::MD5::md5_hex( $s );
1343  
1344 2 return $hex;
1345 }
1346  
1347 sub sha1_hex
1348 2 ▶{
Subroutine sha1_hex: called CC=1 SCAR=0.0
Pod undocumented
1349 2 my $s = shift;
1350  
1351 2 my $hex = Digest::SHA1::sha1_hex( $s );
1352  
1353 2 return $hex;
1354 }
1355  
1356 sub __digest_hex_file
1357 4 ▶{
Subroutine __digest_hex_file: called CC=2 SCAR=6.9
1358 4 my $digest = shift;
1359 4 my $fn = shift;
1360  
1361 4 ▶ open( my $fh, '<', $fn ) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $fn or return undef 3 1 4
1362 3 binmode $fh;
1363 3 $digest->addfile( $fh );
1364 3 return $digest->hexdigest;
1365 }
1366  
1367 sub wp_hex_file
1368 1 ▶{
Subroutine wp_hex_file: called CC=1 SCAR=0.0
Pod undocumented
1369 1 return __digest_hex_file( Digest->new( 'Whirlpool' ), shift() );
1370 }
1371  
1372 sub md5_hex_file
1373 2 ▶{
Subroutine md5_hex_file: called CC=1 SCAR=0.0
Pod undocumented
1374 2 return __digest_hex_file( Digest::MD5->new, shift() );
1375 }
1376  
1377 sub sha1_hex_file
1378 1 ▶{
Subroutine sha1_hex_file: called CC=1 SCAR=0.0
Pod undocumented
1379 1 return __digest_hex_file( Digest::SHA1->new, shift() );
1380 }
1381  
1382 ##############################################################################
1383  
1384 sub create_random_id
1385 5 ▶{
Subroutine create_random_id: called CC=4 SCAR=13.9
Pod undocumented
1386 5 ▶ my $len = shift() || 128;
Condition100%2/2
shift() || 128
l!l
41
MC/DC100%1/1
shift() || 128
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
1387 5 ▶ my $let = shift() || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
Condition100%2/2
shift() || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
l!l
14
MC/DC100%1/1
shift() || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
1388  
1389 5 my $l = length( $let );
1390  
1391 5 my $id;
1392 5 $id .= substr( $let, int(rand() * $l), 1 ) for ( 1 .. $len );
1393 5 return $id;
1394 };
1395  
1396 sub create_random_binary
1397 1 ▶{
Subroutine create_random_binary: called CC=2 SCAR=6.9
Pod undocumented
1398 1 my $len = shift();
1399  
1400 1 my $bin;
1401 1 $bin .= chr( int rand( 256 ) ) for ( 1 .. $len );
1402 1 return $bin;
1403 };
1404  
1405 ##############################################################################
1406  
1407 sub __glob_tree_tree_walk
1408 12 ▶{
Subroutine __glob_tree_tree_walk: called CC=6 SCAR=17.9
1409 12 my $p = shift; # path
1410 12 my $f = shift; # file mask
1411 12 my $r = shift; # result arr-ref
1412 12 my $s = shift; # dirs already on this branch, { "dev:ino" => 1 }
1413  
1414 #print STDERR "DEBUG: __glob_tree_tree_walk: $p -- $f [$p$f]\n";
1415  
1416 12 push @$r, grep { -e } sort ( File::Glob::bsd_glob( "$p$f" ) );
1417  
1418 12 for my $e ( read_dir_entries( "$p/." ) )
1419 {
1420 21 ▶ next unless defined $e;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $e 0 21 21
1421 21 my $ep = "$p$e";
1422 21 ▶ next unless -d $ep;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $ep 10 11 21
1423  
1424 # stat( _ ) reuses the buffer filled by -d above, so this costs no syscall.
1425 # -d follows symlinks, so this is the identity of the directory we would
1426 # descend into, which is exactly what has to be checked for a loop
1427 11 my @st = stat( _ );
1428 11 ▶ next unless @st;
Branch: 1 branch
BranchTrueFalseTotal
unless @st 0 11 11
1429 11 my $id = "$st[0]:$st[1]";
1430  
1431 11 ▶ next if $s->{ $id }; # already an ancestor on this branch -- symlink loop
Branch: 1 branch
BranchTrueFalseTotal
if $s->{$id} 1 10 11
1432  
1433 10 $s->{ $id } = 1;
1434 10 __glob_tree_tree_walk( "$ep/", $f, $r, $s );
1435 10 delete $s->{ $id }; # left the branch, the dir may appear on another one
1436 }
1437  
1438 12 return 1;
1439 }
1440  
1441 sub glob_tree
1442 2 ▶{
Subroutine glob_tree: called CC=4 SCAR=14.0
Pod undocumented
1443 2 my @res;
1444 2 for( @_ )
1445 {
1446 2 ▶ die "glob_tree: invalid argument" unless /^(.*?\/)([^\/]+)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless m[^(.*?/)([^/]+)$] 0 2 2
1447 2 my $p = $1;
1448 2 my $f = $2;
1449  
1450 # per argument, so overlapping arguments still each produce their results
1451 2 my %seen;
1452 2 my @st = stat( $p );
1453 2 ▶ $seen{ "$st[0]:$st[1]" } = 1 if @st;
Branch: 1 branch
BranchTrueFalseTotal
if @st 2 0 2
1454  
1455 2 __glob_tree_tree_walk( $p, $f, \@res, \%seen );
1456 }
1457 2 return @res;
1458 }
1459  
1460 sub read_dir_entries
1461 13 ▶{
Subroutine read_dir_entries: called CC=2 SCAR=7.0
Pod undocumented
1462 13 my $p = shift; # path
1463  
1464 13 ▶ opendir( my $dir, $p ) or return ();
Branch: 1 branch
BranchTrueFalseTotal
opendir my $dir, $p or return () 13 0 13
1465 13 my @e = sort grep { !/^\.\.?$/ } readdir $dir;
1466 13 closedir( $dir );
1467  
1468 13 return @e;
1469 }
1470  
1471 ##############################################################################
1472  
1473 use constant
1474 3 ▶{
Subroutine BEGIN: called CC=1 SCAR=0.0
1475 3 FFT_FILES => 0x01,
1476 FFT_DIRS => 0x02,
1477  
1478 FFT_SYMF => 0x04, # allow symlink files in result (requires FFT_FILES)
1479 FFT_SYMD => 0x08, # allow symlink dirs in result (requires FFT_DIRS )
1480  
1481 FFT_FOLLOW => 0x10,
1482 FFT_DEBUG => 0x80,
1483  
1484 FFT_ALL => 0x01 | 0x02,
1485 FFT_ALLF => 0x01 | 0x04,
1486 FFT_ALLD => 0x02 | 0x08,
1487 FFT_ALL4 => 0x01 | 0x02 | 0x04 | 0x08,
1488 FFT_FULL => 0x01 | 0x02 | 0x04 | 0x08 | 0x10,
1489 3 };
1490  
1491 sub __fftwalk
1492 34 ▶{
Subroutine __fftwalk: called CC=18 SCAR=29.3
1493 34 my $e = shift; # directory entry to traverse
1494 34 my $a = shift; # results array ref
1495 34 my $ty = shift; # typemap, see FFTs above
1496 34 my $s = shift; # dirs already on this branch, { "dev:ino" => 1 }
1497  
1498 34 ▶ print "debug: __fftwalk [$e]\n" if $ty & FFT_DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $ty & 128 0 34 34
1499  
1500 34 ▶ opendir( my $dir, $e ) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
opendir my $dir, $e or return undef 34 0 34
1501 34 my $ee;
1502 34 ▶ while( $ee = readdir $dir )
Branch: 1 branch
BranchTrueFalseTotal
if (defined($ee = readdir $dir)) 128 34 162
1503 {
1504 128 ▶ next if $ee eq '.' or $ee eq '..';
Branch: 1 branch
BranchTrueFalseTotal
if $ee eq "." or $ee eq ".." 68 60 128
Condition100%3/3
$ee eq "." or $ee eq ".."
l!l&&r!l&&!r
343460
MC/DC100%2/2
$ee eq "." or $ee eq ".."
$ee eq "." $ee eq ".."
Truth table100%3/3
A or B
A= $ee eq "."B= $ee eq ".."
ABresult
1X1
011
000
1505 60 my $eee = "$e/$ee";
1506  
1507 60 my $is_dir = -d $eee;
1508 # stat( _ ) reuses the buffer filled by -d, so this costs no syscall and
1509 # must be read before -l below, which refills the buffer with lstat data
1510 60 ▶ my @st = $is_dir ? stat( _ ) : ();
Branch: 1 branch
BranchTrueFalseTotal
$is_dir ? : 32 28 60
1511 60 my $is_link = -l $eee;
1512  
1513 60 ▶ if( $is_dir )
Branch: 1 branch
BranchTrueFalseTotal
if ($is_dir) { } 32 28 60
1514 {
1515 32 ▶ push @$a, $eee if $is_link ? $ty & FFT_DIRS && $ty & FFT_SYMD : $ty & FFT_DIRS;
Branch: 2 branches
BranchTrueFalseTotal
if $is_link ? $ty & 2 && $ty & 8 : $ty & 2 19 13 32
$is_link ? : 6 26 32
Condition66%2/3
$ty & 2 and $ty & 8
!ll&&!rl&&r
033
MC/DC50%1/2
$ty & 2 and $ty & 8
$ty & 2 $ty & 8
Truth table66%2/3
A and B
A= $ty & 2B= $ty & 8
ABresult
0X0
100
111
1516  
1517 32 ▶ next unless ! $is_link or $ty & FFT_FOLLOW;
Branch: 1 branch
BranchTrueFalseTotal
unless not $is_link or $ty & 16 3 29 32
Condition100%3/3
not $is_link or $ty & 16
l!l&&r!l&&!r
2633
MC/DC100%2/2
not $is_link or $ty & 16
not $is_link $ty & 16
Truth table100%3/3
not(A) or B
A= not $is_linkB= $ty & 16
ABresult
1X1
011
000
1518 29 ▶ next unless @st;
Branch: 1 branch
BranchTrueFalseTotal
unless @st 0 29 29
1519 29 my $id = "$st[0]:$st[1]";
1520  
1521 29 ▶ next if $s->{ $id }; # already an ancestor on this branch -- symlink loop
Branch: 1 branch
BranchTrueFalseTotal
if $s->{$id} 1 28 29
1522  
1523 28 $s->{ $id } = 1;
1524 28 __fftwalk( $eee, $a, $ty, $s );
1525 28 delete $s->{ $id }; # left the branch, the dir may appear on another one
1526 }
1527 else
1528 {
1529 28 ▶ push @$a, $eee if $is_link ? $ty & FFT_FILES && $ty & FFT_SYMF : $ty & FFT_FILES;
Branch: 2 branches
BranchTrueFalseTotal
if $is_link ? $ty & 1 && $ty & 4 : $ty & 1 23 5 28
$is_link ? : 0 28 28
Condition0%0/3
$ty & 1 and $ty & 4
!ll&&!rl&&r
000
MC/DC0%0/2
$ty & 1 and $ty & 4
$ty & 1 $ty & 4
Truth table0%0/3
A and B
A= $ty & 1B= $ty & 4
ABresult
0X0
100
111
1530 }
1531 }
1532 34 closedir( $dir );
1533 }
1534  
1535 # fast file tree walk
1536 # * first argument is traversal typemap scalar or hash with options
1537 # * rest of arguments are directory names to be walked
1538 #
1539 # examples:
1540 # my $res_arrref = fftwalk( FFT_FILES | FFT_SYMF, 'go', 'now/' );
1541 # fftwalk( { TYPE => FFT_FULL, ARRAY => \@res_arr }, 'go', 'now/' );
1542 #
1543 # options hash can have:
1544 # TYPE => typemap
1545 # this option tells which types of filesystem entries to be processed:
1546 # FFT_FILES -- add found files
1547 # FFT_DIRS -- add found directories
1548 # FFT_SYMF -- add found file symlinks (needs FFT_FILES)
1549 # FFT_SYMD -- add found dir symlinks (needs FFT_DIRS )
1550 # FFT_FOLLOW -- follow/traverse symlink dirs
1551 # there are few shortcut options (those above, combined):
1552 # FFT_ALL -- all files and dirs but no symlinks
1553 # FFT_ALLF -- all files and file symlinks
1554 # FFT_ALLD -- all dirs and dir symlinks
1555 # FFT_ALL4 -- all files and dirs including symlinks
1556 # FFT_FULL -- all files, dirs, symlinks and follow symlink dirs
1557 # if TYPE is zero, fftwalk will not do anything
1558 # ARRAY => hashref_to_append_result_list
1559  
1560 sub fftwalk
1561 7 ▶{
Subroutine fftwalk: called CC=7 SCAR=19.5
Pod undocumented
1562 7 my $ty = shift;
1563  
1564 7 my $opt = {};
1565 7 ▶ if( ref( $ty ) eq 'HASH' )
Branch: 1 branch
BranchTrueFalseTotal
if (ref $ty eq 'HASH') { } 1 6 7
1566 {
1567 1 $opt = $ty;
1568 1 $ty = $opt->{ 'TYPE' };
1569 }
1570 else
1571 {
1572 6 $opt = {};
1573 }
1574  
1575 7 ▶ die "fftwalk() uses TYPE instead of MODE" if $opt->{ 'MODE' };
Branch: 1 branch
BranchTrueFalseTotal
if $opt->{"MODE"} 0 7 7
1576  
1577 7 ▶ my $a = $opt->{ 'ARRAY' } ? $opt->{ 'ARRAY' } : [];
Branch: 1 branch
BranchTrueFalseTotal
$opt->{'ARRAY'} ? : 1 6 7
1578  
1579 7 ▶ return $a unless $ty > 0; # do nothing if TYPE is zero
Branch: 1 branch
BranchTrueFalseTotal
unless $ty > 0 1 6 7
1580  
1581 6 for my $e ( @_ )
1582 {
1583 # per start directory, so several start dirs still each produce results
1584 6 my %seen;
1585 6 my @st = stat( $e );
1586 6 ▶ $seen{ "$st[0]:$st[1]" } = 1 if @st;
Branch: 1 branch
BranchTrueFalseTotal
if @st 6 0 6
1587  
1588 6 __fftwalk( $e, $a, $ty, \%seen );
1589 }
1590 6 return $a;
1591 }
1592  
1593 ##############################################################################
1594  
1595 sub ref_freeze
1596 2 ▶{
Subroutine ref_freeze: called CC=2 SCAR=6.9
Pod undocumented
1597 2 my $ref = shift;
1598  
1599 2 ▶ die "error: ref_freeze(): requires data reference!\n" unless ref( $ref );
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ref 1 1 2
1600  
1601 1 my $fzd = encode_base64( Storable::nfreeze( $ref ) );
1602 };
1603  
1604 sub ref_thaw
1605 1 ▶{
Subroutine ref_thaw: called CC=2 SCAR=7.1
Pod undocumented
1606 1 my $fzd = shift;
1607  
1608 1 my ( $ref ) = Storable::thaw( decode_base64( $fzd ), 0 ); # disable bless and tie, was always used for data only
1609  
1610 1 ▶ return ref( $ref ) ? $ref : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $ref ? : 1 0 1
1611 };
1612  
1613 ##############################################################################
1614  
1615 sub int2hex
1616 2 ▶{
Subroutine int2hex: called CC=1 SCAR=0.0
Pod undocumented
1617 2 return sprintf( "%X", shift );
1618 }
1619  
1620 3 *hex2int = *CORE::hex;
1621  
1622 ##############################################################################
1623  
1624 sub bcd2int
1625 304 ▶{
Subroutine bcd2int: called CC=2 SCAR=6.9
Pod undocumented
1626 304 my $bcd = shift;
1627  
1628 304 my $int = 0;
1629  
1630 304 my @bcd = unpack 'C*', $bcd;
1631 304 my $p = @bcd * 2 - 1;
1632 304 for( @bcd )
1633 {
1634 515 $int += ( 10 ** $p-- ) * ( ( $_ & 0xF0 ) >> 4 );
1635 515 $int += ( 10 ** $p-- ) * ( ( $_ & 0x0F ) );
1636 }
1637  
1638 304 return $int;
1639 }
1640  
1641 # int2bcd( $int, $len )
1642 # produces packed BCD, two decimal digits per byte, most significant first,
1643 # i.e. the exact inverse of bcd2int(). $len is the wanted result size in bytes,
1644 # the result is left padded with zeroes to reach it. if $len is omitted the
1645 # smallest size that holds the number is used. $int is taken as a decimal
1646 # string, so numbers wider than an integer still convert exactly, as long as
1647 # they are passed as strings -- a bare numeric literal is numified by perl
1648 # before it ever reaches here.
1649 sub int2bcd
1650 313 ▶{
Subroutine int2bcd: called CC=6 SCAR=17.9
Pod undocumented
1651 313 my $int = shift;
1652 313 my $len = shift; # in how many bytes to produce bcd, optional
1653  
1654 313 ▶ die "int2bcd(): expected a non-negative integer, got [$int]\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $int =~ /^\s*\+?(\d+)\s*$/ 2 311 313
1655 unless $int =~ /^\s*\+?(\d+)\s*$/;
1656  
1657 311 my $str = $1;
1658 311 $str =~ s/^0+(?=\d)//; # strip leading zeroes but keep a single 0
1659  
1660 311 ▶ if( defined $len )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $len) { } 4 307 311
1661 {
1662 4 ▶ die "int2bcd(): expected a positive byte length, got [$len]\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $len =~ /^\s*\+?(\d+)\s*$/ and $1 > 0 1 3 4
Condition66%2/3
$len =~ /^\s*\+?(\d+)\s*$/ and $1 > 0
!ll&&!rl&&r
013
MC/DC50%1/2
$len =~ /^\s*\+?(\d+)\s*$/ and $1 > 0
$len =~ /^\s*\+?(\d+)\s*$/ $1 > 0
Truth table66%2/3
A and B
A= $len =~ /^\s*\+?(\d+)\s*$/B= $1 > 0
ABresult
0X0
100
111
1663 unless $len =~ /^\s*\+?(\d+)\s*$/ and $1 > 0;
1664 3 $len = $1;
1665 3 ▶ die "int2bcd(): [$str] needs more than [$len] bytes\n" if length( $str ) > $len * 2;
Branch: 1 branch
BranchTrueFalseTotal
if length $str > $len * 2 1 2 3
1666 }
1667 else
1668 {
1669 307 $len = int( ( length( $str ) + 1 ) / 2 );
1670 }
1671  
1672 309 return pack 'H*', ( '0' x ( $len * 2 - length( $str ) ) ) . $str;
1673 }
1674  
1675 sub bcd2str
1676 3 ▶{
Subroutine bcd2str: called CC=2 SCAR=6.9
Pod undocumented
1677 3 my $bcd = shift;
1678  
1679 3 my $str;
1680  
1681 3 my @bcd = unpack 'C*', $bcd;
1682 3 for( @bcd )
1683 {
1684 14 $str .= ( ( $_ & 0xF0 ) >> 4 );
1685 14 $str .= ( ( $_ & 0x0F ) );
1686 }
1687  
1688 3 return $str;
1689 }
1690  
1691 ##############################################################################
1692  
1693 # sub format_ascii_table
1694 # takes either arrayref-of-arraysrefs or arrayref-oh-hashrefs
1695 # first row is heading, not special, just will have separator line after it
1696 # zero (before first) row is optional and holds formatting. by default it is
1697 # disabled, need format_ascii_table( \@data, FMT => 1 ); to be enabled
1698 # current format values are:
1699 # < align left (empty value is considered left align)
1700 # > align right
1701 # | align center
1702 # any number present will be used as column width in chars
1703  
1704 sub format_ascii_table
1705 3 ▶{
Subroutine format_ascii_table: called CC=23 SCAR=31.4
Pod undocumented
1706 3 my $data = shift;
1707 3 my %opt = @_;
1708  
1709 3 ▶ $data = format_ascii_convert_aoh_to_aoa( $data ) if ref( $data->[ 0 ] ) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $data->[0] eq "HASH" 1 2 3
1710  
1711 3 my @fma; # format align
1712 my @fmw; # format width
1713  
1714 3 my $wt; # width total
1715 3 my $cs; # columns
1716  
1717 3 my $r;
1718  
1719 3 $r = 0;
1720 3 for my $row ( @$data )
1721 {
1722 9 ▶ if( $opt{ 'FMT' } and $r == 0 )
Branch: 1 branch
BranchTrueFalseTotal
if ($opt{"FMT"} and $r == 0) 1 8 9
Condition100%3/3
$opt{"FMT"} and $r == 0
!ll&&!rl&&r
621
MC/DC100%2/2
$opt{"FMT"} and $r == 0
$opt{"FMT"} $r == 0
Truth table100%3/3
A and B
A= $opt{"FMT"}B= $r == 0
ABresult
0X0
100
111
1723 {
1724 1 for( @$row )
1725 {
1726 2 my ( $a, $w ) = ( '<', 0 );
1727 2 ▶ ( $a, $w ) = ( $1, $2 ) if /^\s*([<>\|])\s*(\d+)?/;
Branch: 1 branch
BranchTrueFalseTotal
if /^\s*([<>\|])\s*(\d+)?/ 2 0 2
1728 2 push @fma, $a;
1729 2 push @fmw, $w;
1730 }
1731 1 $r++;
1732 1 next;
1733 }
1734 8 my $c = 0;
1735 8 for my $d ( @$row )
1736 {
1737 16 my $l = length( $d );
1738 16 ▶ $fmw[ $c ] = $l if $l > $fmw[ $c ]; # expand format widths if needed
Branch: 1 branch
BranchTrueFalseTotal
if $l > $fmw[$c] 5 11 16
1739 16 $c++;
1740 }
1741 8 ▶ $cs = $c if $c > $cs;
Branch: 1 branch
BranchTrueFalseTotal
if $c > $cs 3 5 8
1742 8 $r++;
1743 }
1744  
1745 3 $wt += $_ + 2 for @fmw; # plus 2 for one char spacing around borders
1746 3 $wt += @fmw + 1; # plus border chars
1747  
1748 3 my $sep = '+' . ( '-' x ( $wt - 2 ) ) . '+' . "\n";
1749 3 my $tx;
1750  
1751 3 $r = 0;
1752 3 $tx .= $sep;
1753 3 for my $row ( @$data )
1754 {
1755 9 ▶ $r++, next if $opt{ 'FMT' } and $r == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $opt{"FMT"} and $r == 0 1 8 9
Condition100%3/3
$opt{"FMT"} and $r == 0
!ll&&!rl&&r
621
MC/DC100%2/2
$opt{"FMT"} and $r == 0
$opt{"FMT"} $r == 0
Truth table100%3/3
A and B
A= $opt{"FMT"}B= $r == 0
ABresult
0X0
100
111
1756 8 $tx .= '|';
1757 8 for my $c ( 0 .. $cs - 1 )
1758 {
1759 16 my $v = $row->[ $c ];
1760  
1761 16 my $a = $fma[ $c ];
1762 16 my $w = $fmw[ $c ];
1763 16 ▶ $a = '>' if ! $a and $v =~ /^([\+\-])?[\d\.]+$/;
Branch: 1 branch
BranchTrueFalseTotal
if not $a and $v =~ /^([\+\-])?[\d\.]+$/ 4 12 16
Condition100%3/3
not $a and $v =~ /^([\+\-])?[\d\.]+$/
!ll&&!rl&&r
484
MC/DC100%2/2
not $a and $v =~ /^([\+\-])?[\d\.]+$/
not $a $v =~ /^([\+\-])?[\d\.]+$/
Truth table100%3/3
not(A) and B
A= not $aB= $v =~ /^([\+\-])?[\d\.]+$/
ABresult
0X0
100
111
1764 16 ▶ $a = '<' if ! $a;
Branch: 1 branch
BranchTrueFalseTotal
unless $a 8 8 16
1765  
1766 16 ▶ $v = str_pad( $v, $w ) if $a eq '<';
Branch: 1 branch
BranchTrueFalseTotal
if $a eq "<" 8 8 16
1767 16 ▶ $v = str_pad( $v, - $w ) if $a eq '>';
Branch: 1 branch
BranchTrueFalseTotal
if $a eq ">" 6 10 16
1768 16 ▶ $v = str_pad_center( $v, $w ) if $a eq '|';
Branch: 1 branch
BranchTrueFalseTotal
if $a eq "|" 2 14 16
1769  
1770 16 $tx .= ' ' . $v . ' |';
1771 }
1772 8 $tx .= "\n";
1773 8 ▶ $tx .= $sep if $r == ( $opt{ 'FMT' } ? 1 : 0 );
Branch: 2 branches
BranchTrueFalseTotal
if $r == ($opt{"FMT"} ? 1 : 0) 3 5 8
$opt{'FMT'} ? : 2 6 8
1774 8 $r++;
1775 }
1776 3 $tx .= $sep;
1777  
1778 3 return $tx;
1779 }
1780  
1781 sub format_ascii_convert_aoh_to_aoa
1782 1 ▶{
Subroutine format_ascii_convert_aoh_to_aoa: called CC=4 SCAR=13.9
Pod undocumented
1783 1 my $data = shift;
1784 1 my @out;
1785  
1786 my %keys;
1787 1 for my $row ( @$data )
1788 {
1789 2 $keys{ $_ }++ for keys %$row;
1790 }
1791 1 my @keys = sort keys %keys;
1792  
1793 1 push @out, \@keys;
1794 1 for my $row ( @$data )
1795 {
1796 2 push @out, [ map { $row->{ $_ } } @keys ];
1797 }
1798  
1799 1 return \@out;
1800 }
1801  
1802 ##############################################################################
1803  
1804 sub eval_err_strip
1805 7 ▶{
Subroutine eval_err_strip: called CC=2 SCAR=6.9
Pod undocumented
1806 7 ▶ my $err = shift || return undef;
Condition100%2/2
shift() || (return undef)
l!l
52
MC/DC100%1/1
shift() || (return undef)
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
1807 5 $err =~ s/\n.*//s;
1808 5 $err =~ s/ \(\@INC[^)]*\)//;
1809 5 $err =~ s/ at \S+ line \d+.*//;
1810 5 return $err;
1811 }
1812  
1813 ##############################################################################
1814  
1815 3 ▶BEGIN { __url_escapes_init(); }
Subroutine BEGIN: called CC=1 SCAR=0.0
1816 3 ▶INIT { __url_escapes_init(); }
Subroutine INIT: called CC=1 SCAR=0.0
1817  
1818 ##############################################################################
1819  
1820 =pod
1821  
1822  
1823 =head1 NAME
1824  
1825 Data::Tools provides set of basic functions for data manipulation.
1826  
1827 =head1 SYNOPSIS
1828  
1829 use Data::Tools qw( :all ); # import all functions
1830 use Data::Tools; # the same as :all :)
1831 use Data::Tools qw( :none ); # do not import anything, use full package names
1832  
1833 # --------------------------------------------------------------------------
1834  
1835 # these set the encoding used by the file_text_* functions only:
1836  
1837 data_tools_set_text_io_encoding( 'UTF-8' ); # file_text_* io will use UTF-8
1838 data_tools_set_text_io_utf8(); # the same, shortcut
1839 data_tools_set_text_io_bin(); # file_text_* io will use binary data
1840  
1841 my $res = file_save( $file_name, 'file content here' );
1842 my $data = file_load( $file_name );
1843  
1844 my $data_arrayref = file_load_ar( $file_name );
1845  
1846 # for specific charset encoding and because of backward compatibility:
1847  
1848 my $res = file_save( { FILE_NAME => $file_name, ENCODING => 'UTF-8' }, 'data' );
1849 my $data = file_load( { FILE_NAME => $file_name, ENCODING => 'UTF-8' } );
1850  
1851 my $data_arrayref = file_load_ar( { FILE_NAME => $fname, ENCODING => 'UTF-8' } );
1852  
1853 # ':RAW' => 1 reads/writes binary data:
1854  
1855 my $res = file_save( { FILE_NAME => $file_name, ':RAW' => 1 }, $binary_data );
1856 my $data = file_load( { FILE_NAME => $file_name, ':RAW' => 1 } );
1857  
1858 # --------------------------------------------------------------------------
1859  
1860 my $file_modification_time_in_seconds = file_mtime( $file_name );
1861 my $file_change_time_in_seconds = file_ctime( $file_name );
1862 my $file_last_access_time_in_seconds = file_atime( $file_name );
1863 my $file_size = file_size( $file_name );
1864  
1865 # --------------------------------------------------------------------------
1866  
1867 my $res = dir_path_make( '/path/to/somewhere' ); # create full path with 0700
1868 my $res = dir_path_make( '/new/path', MASK => 0755 ); # ...with mask 0755
1869 my $path = dir_path_ensure( '/path/s/t/h' ); # ensure path exists, check+make
1870  
1871 # --------------------------------------------------------------------------
1872  
1873 my $path_with_trailing_slash = file_path( $full_path_or_file_name );
1874  
1875 # file_name() and file_name_ext() return full name with leadeing
1876 # dot for dot-files ( .filename )
1877 my $file_name_including_ext = file_name_ext( $full_path_or_file_name );
1878 my $file_name_only_no_ext = file_name( $full_path_or_file_name );
1879  
1880 # file_ext() returns undef for dot-files ( .filename )
1881 my $file_ext_only = file_ext( $full_path_or_file_name );
1882  
1883 # --------------------------------------------------------------------------
1884  
1885 # uses simple backslash escaping of \n, = and \ itself
1886 my $data_str = hash2str( $hash_ref ); # convert hash to string "key=value\n"
1887 my $hash_ref = str2hash( $hash_str ); # convert str "key-value\n" to hash
1888  
1889 # same as hash2str() but uses keys in certain order
1890 my $data_str = hash2str_keys( \%hash, sort keys %hash );
1891 my $data_str = hash2str_keys( \%hash, sort { $a <=> $b } keys %hash );
1892  
1893 # same as hash2str() and str2hash() but uses URL-style escaping
1894 my $data_str = hash2str_url( $hash_ref ); # convert hash to string "key=value\n"
1895 my $hash_ref = str2hash_url( $hash_str ); # convert str "key-value\n" to hash
1896  
1897 my $hash_ref = url2hash( 'key1=val1&key2=val2&testing=tralala);
1898 # $hash_ref will be { key1 => 'val1', key2 => 'val2', testing => 'tralala' }
1899  
1900 my $hash_ref_with_upper_case_keys = hash_uc( $hash_ref_with_lower_case_keys );
1901 my $hash_ref_with_lower_case_keys = hash_lc( $hash_ref_with_upper_case_keys );
1902  
1903 hash_uc_ipl( $hash_ref_to_be_converted_to_upper_case_keys );
1904 hash_lc_ipl( $hash_ref_to_be_converted_to_lower_case_keys );
1905  
1906 # save/load hash in str_url_escaped form to/from a file
1907 my $res = hash_save( $file_name, $hash_ref );
1908 my $hash_ref = hash_load( $file_name );
1909  
1910 # save hash with certain keys order, uses hash2str_keys()
1911 my $res = hash_save( $file_name, \%hash, sort keys %hash );
1912  
1913 # same as hash_save() and hash_load() but uses hash2str_url() and str2hash_url()
1914 my $res = hash_save_url( $file_name, $hash_ref );
1915 my $hash_ref = hash_load_url( $file_name );
1916  
1917 # validate (nested) hash by example
1918  
1919 # validation example nested hash
1920 my $validate_hr = {
1921 A => 'INT',
1922 B => 'INT(-5,10)',
1923 C => 'REAL',
1924 D => {
1925 E => 'RE:\d+[a-f]*', # regexp match
1926 F => 'REI:\d+[a-f]*', # case insensitive regexp match
1927 },
1928 DIR1 => '-d', # must be existing directory
1929 DIR2 => 'dir', # must be existing directory
1930 FILE1 => '-f', # must be existing file
1931 FILE2 => 'file', # must be existing file
1932 };
1933 # actual nested hash to be verified if looks like the example
1934 my $data_hr = {
1935 A => '123',
1936 B => '-1',
1937 C => '1 234 567.89',
1938 D => {
1939 E => '123abc',
1940 F => '456FFF',
1941 },
1942 }
1943  
1944 my @invalid_keys = hash_validate( $data_hr, $validate_hr );
1945 print "YES!" if hash_validate( $data_hr, $validate_hr );
1946  
1947 # --------------------------------------------------------------------------
1948  
1949 my $escaped = str_url_escape( $plain_str ); # URL-style %XX escaping
1950 my $plain_str = str_url_unescape( $escaped );
1951  
1952 # NOTE: url (RFC 3986) is ascii only, anything else is UTF-8 bytes as %xx.
1953 # str_url_escape() encodes characters (perl utf8 string) to UTF-8
1954 # bytes first, a non-utf8 string is taken as bytes and escaped as it
1955 # is, so UTF-8 bytes are not encoded twice. characters below 0x100 may
1956 # be kept without the utf8 flag (literal "\x{e9}"), then they are bytes:
1957 # str_url_escape( "\x{e9}" ) is "%E9", use utf8::upgrade() or decode()
1958 # for text, then it is "%C3%A9".
1959 # str_url_unescape() takes url (ascii or UTF-8 bytes) and returns
1960 # characters: %xx escapes become bytes, decoded from UTF-8, invalid
1961 # bytes become U+FFFD: str_url_unescape( "%D0%98" ) is "\x{418}".
1962 # characters (perl utf8 string) in its input are encoded to UTF-8 bytes
1963 # first, so raw text mixed with %xx escapes is kept.
1964 # str_url_unescape( str_url_escape( $text ) ) returns $text.
1965 # url2hash() and str2hash_url() use str_url_unescape() and return
1966 # characters too.
1967  
1968 my $escaped = str_html_escape( $plain_str ); # HTML-style &name; escaping
1969 my $plain_str = str_html_unescape( $escaped );
1970  
1971 my $hex_str = str_hex( $plain_str ); # HEX-style XX string escaping
1972 my $plain_str = str_unhex( $hex_str );
1973  
1974 my $hex_str = str_hex_utf8( $text ); # the same for text (wide chars)
1975 my $text = str_unhex_utf8( $hex_str );
1976  
1977 # NOTE: str_hex() and str_unhex() work on bytes, i.e. unpack/pack( "H*" ):
1978 # characters above 0xFF are wrapped to their low byte, so different
1979 # text may give the same result: str_hex( "\x{430}\x{430}" ) and
1980 # str_hex( "00" ) both return "3030". use them for binary data only.
1981 # str_hex_utf8() encodes text to UTF-8 bytes first, so the result is
1982 # unique per text: str_hex_utf8( "\x{430}\x{430}" ) returns "d0b0d0b0".
1983 # str_unhex_utf8() decodes the bytes back to text, invalid UTF-8 bytes
1984 # become U+FFFD. results differ from str_hex() for any non-ASCII text,
1985 # str_hex( "\x{e9}" ) is "e9" while str_hex_utf8( "\x{e9}" ) is "c3a9".
1986 # str_unhex() and str_unhex_utf8() do not check their input: odd length
1987 # is padded with "0" ( "414" gives "A@" ) and non-hex characters are
1988 # not rejected but silently converted to garbage bytes.
1989  
1990 # --------------------------------------------------------------------------
1991  
1992 # converts perl package names to file names, f.e: returns "Data/Tools.pm"
1993 my $perl_pkg_fn = perl_package_to_file( 'Data::Tools' );
1994  
1995 # --------------------------------------------------------------------------
1996  
1997 # calculating hex digests
1998 my $whirlpool_hex = wp_hex( $data );
1999 my $sha1_hex = sha1_hex( $data );
2000 my $md5_hex = md5_hex( $data );
2001  
2002 # --------------------------------------------------------------------------
2003  
2004 my $formatted_str = str_num_comma( 1234567.89 ); # returns "1'234'567.89"
2005 my $formatted_str = str_num_comma( 4325678, '_' ); # returns "4_325_678"
2006 my $padded_str = str_pad( 'right', -12, '*' ); # returns "right*******"
2007 my $str_c = str_countable( $dc, 'day', 'days' );
2008 # returns 'days' for $dc == 0
2009 # returns 'day' for $dc == 1
2010 # returns 'days' for $dc > 1
2011  
2012 my $num = str_kmg_to_num( '1K' ); # returns 1024
2013 my $num = str_kmg_to_num( '2.5M' ); # returns 2621440
2014 my $num = str_kmg_to_num( '1T' ); # returns 1099511627776
2015  
2016 # --------------------------------------------------------------------------
2017  
2018 # find all *.txt files in all subdirectories starting from /usr/local
2019 # returned files are with full path names
2020 my @files = glob_tree( '/usr/local/*.txt' );
2021  
2022 # read directory entries names (without full paths)
2023 my @files_and_dirs = read_dir_entries( '/tmp/secret/dir' );
2024  
2025 # --------------------------------------------------------------------------
2026  
2027 my $int = bcd2int( $bcd_bytes ); # convert BCD byte data to integer
2028 my $bytes = int2bcd( $int ); # convert integer to BCD bytes
2029 my $str = bcd2str( $bcd_bytes ); # convert BCD byte data to string
2030  
2031 =head1 FUNCTIONS
2032  
2033 =head2 hash_validate( $data_hr, $validate_hr );
2034  
2035 Return value can be either scalar or array context. In scalar context return
2036 value is true (1) or false (0). In array context it returns list of the invalid
2037 keys (possibly key paths like 'KEY1/KEY2/KEY3'):
2038  
2039 # array context
2040 my @invalid_keys = hash_validate( $data_hr, $validate_hr );
2041  
2042 # scalar context
2043 print "YES!" if hash_validate( $data_hr, $validate_hr );
2044  
2045 =head1 TODO
2046  
2047 (more docs)
2048  
2049 =head1 DATA::TOOLS SUB-MODULES
2050  
2051 Data::Tools package includes several sub-modules:
2052  
2053 * Data::Tools::Time (time processing)
2054 * Data::Tools::Math (mathematics)
2055 * Data::Tools::CSV (compact, pure-perl CSV parsing)
2056 * Data::Tools::Serialization (high-level serialization)
2057  
2058 Since 1.60 process and socket modules are separate packages:
2059  
2060 * Data-Tools-Process Data::Tools::Process, Data::Tools::Process::Forks,
2061 Data::Tools::Process::ForkPool
2062 * Net-Tools Net::Tools::Socket, Net::Tools::Socket::Protocols,
2063 Net::Tools::Socket::Pair, Net::Tools::Socket::Err
2064 (were Data::Tools::Socket*)
2065  
2066 =head1 REQUIRED MODULES
2067  
2068 Data::Tools is designed to be simple, compact and self sufficient.
2069 However it uses some 3rd party modules:
2070  
2071 * Digest::Whirlpool
2072 * Digest::MD5
2073 * Digest::SHA1
2074 * JSON
2075  
2076 =head1 SEE ALSO
2077  
2078 For more complex cases of nested hash validation,
2079 check Data::Validate::Struct module by Thomas Linden, cheers :)
2080  
2081 =head1 GITHUB REPOSITORY
2082  
2083 git@github.com:cade-vs/perl-data-tools.git
2084  
2085 git clone git://github.com/cade-vs/perl-data-tools.git
2086  
2087 =head1 AUTHOR
2088  
2089 Vladi Belperchinov-Shabanski "Cade"
2090 <cade@noxrun.com> <cade@bis.bg> <cade@cpan.org>
2091 http://cade.noxrun.com/
2092  
2093  
2094 =cut
2095  
2096 ##############################################################################
2097 3 1;
↑ Summary Tools/CSV.pm »