Acrux/Util.pm

filter: Statementstmt 24.9% 89 / 357 Branchbran 6.3% 12 / 190 Conditioncond 5.5% 8 / 143 MC/DCmcdc 2.6% 2 / 77 Subroutinesub 41.6% 20 / 48 Podpod 100% 33 / 33 totaltotal 19.3% 164 / 848 CC 169 SCAR 48.4
CC
169
Cov
16%
fdt
462.0
spew
342.0
slurp
272.0
CRAP 125.8
« Acme/Crux/Plugin/Log.pm ↑ Summary Acme/Crux.pm »
1 package Acrux::Util;
2 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 5 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 =encoding utf8
6  
7 =head1 NAME
8  
9 Acrux::Util - The Acrux utilities
10  
11 =head1 SYNOPSIS
12  
13 use Acrux::Util;
14  
15 =head1 DESCRIPTION
16  
17 This module provides portable utility functions for Acrux
18  
19 =head2 clone
20  
21 my $copy = clone(\@array);
22 my $copy = clone(\%hash);
23  
24 This function is a proxy function for L<Storable/dclone>
25  
26 It makes recursive copies of nested hash, array, scalar and reference types, including tied variables and objects.
27 The C<clone()> takes a scalar argument and duplicates it. To duplicate lists, arrays or hashes, pass them in by reference, e.g.
28  
29 =head2 color
30  
31 say color(blue => "Format %s %s" => "text", "foo");
32 say color(cyan => "text");
33 say color("red on_bright_yellow" => "text");
34 say STDERR color("red on_bright_yellow" => "text");
35  
36 Returns colored formatted string if is session was runned from terminal
37  
38 Supported normal foreground colors:
39  
40 black, red, green, yellow, blue, magenta, cyan, white
41  
42 Bright foreground colors:
43  
44 bright_black, bright_red, bright_green, bright_yellow
45 bright_blue, bright_magenta, bright_cyan, bright_white
46  
47 Normal background colors:
48  
49 on_black, on_red, on_green, on yellow
50 on_blue, on_magenta, on_cyan, on_white
51  
52 Bright background color:
53  
54 on_bright_black, on_bright_red, on_bright_green, on_bright_yellow
55 on_bright_blue, on_bright_magenta, on_bright_cyan, on_bright_white
56  
57 See also L<Term::ANSIColor>
58  
59 =head2 deprecated
60  
61 deprecated('foo is DEPRECATED in favor of bar');
62  
63 Warn about deprecated feature from perspective of caller.
64 You can also set the C<ACRUX_FATAL_DEPRECATIONS> environment
65 variable to make them die instead with L<Carp>
66  
67 =head2 dformat
68  
69 $string = dformat( $mask, \%replacehash );
70 $string = dformat( $mask, %replacehash );
71  
72 Replace substrings "[...]" in mask and
73 returns replaced result. Data for replacing get from \%replacehash
74  
75 For example:
76  
77 # -> 01-foo-bar.baz.tgz
78 $string = dformat( "01-[NAME]-bar.[EXT].tgz", {
79 NAME => 'foo',
80 EXT => 'baz',
81 });
82  
83 See also L<CTK::Util/dformat>
84  
85 =head2 dtf
86  
87 See L</fdt>
88  
89 =head2 dumper
90  
91 my $perl = dumper({some => 'data'});
92  
93 Dump a Perl data structure with L<Data::Dumper>
94  
95 =head2 eqtime
96  
97 eqtime("from/file", "to/file") or die "Oops";
98  
99 Sets modified time of destination to that of source
100  
101 =head2 fbytes
102  
103 print fbytes( 123456 );
104  
105 Returns formatted size value
106  
107 =head2 fdate
108  
109 print fdate( time );
110  
111 Returns formatted date value
112  
113 =head2 fdatetime
114  
115 print fdatetime( time );
116  
117 Returns formatted date value
118  
119 =head2 fdt
120  
121 print fdt( $format, $time );
122 print fdt( $format, $time, 1 ); # in GMT context
123  
124 Returns time in your format.
125 Each conversion specification is replaced by appropriate characters as described in the following list
126  
127 s, ss, _s - Seconds
128 m, mm, _m - Minutes
129 h, hh, _h - Hours
130 D, DD, _D - Day of month
131 M, MM, _M - Month
132 Y, YY, YYY, YYYY - Year
133 w - Short form of week day (Sat, Tue and etc)
134 W - Week day (Saturdat, Tuesday and etc)
135 MON, mon - Short form of month (Apr, May and etc)
136 MONTH, month - Month (April, May and etc)
137 Z - Diff of TimeZone in short format (+0300)
138 z - Diff of TimeZone in lomg format (+03:00)
139 G - Short name of TimeZone GMT (for GMT context only)
140 U - Short name of TimeZone UTC (for GMT context only)
141  
142 Examples:
143  
144 # RFC822 (RSS)
145 say fdt("%w, %D %MON %YY %hh:%mm:%ss %G", time(), 1); # Tue, 3 Sep 2013 12:31:40 GMT
146  
147 # RFC850
148 say fdt("%W, %DD-%MON-%YY %hh:%mm:%ss %G", time(), 1); # Tuesday, 03-Sep-13 12:38:41 GMT
149  
150 # RFC1036
151 say fdt("%w, %D %MON %YY %hh:%mm:%ss %G", time(), 1); # Tue, 3 Sep 13 12:44:08 GMT
152  
153 # RFC1123
154 say fdt("%w, %D %MON %YYYY %hh:%mm:%ss %G", time(), 1); # Tue, 3 Sep 2013 12:50:42 GMT
155  
156 # RFC2822
157 say fdt("%w, %DD %MON %YYYY %hh:%mm:%ss %Z"); # Tue, 12 Feb 2013 16:07:05 +0400
158 say fdt("%w, %DD %MON %YYYY %hh:%mm:%ss ".tz_diff());
159  
160 # W3CDTF, ATOM (Same as RFC 3339/ISO 8601) -- Mail format
161 say fdt("%YYYY-%MM-%DDT%hh:%mm:%ss%z"); # 2013-02-12T16:10:28+04:00
162  
163 # CTIME
164 say fdt("%w %MON %_D %hh:%mm:%ss %YYYY"); # Tue Feb 2 16:15:18 2013
165  
166 # Russian date and time format
167 say fdt("%DD.%MM.%YYYY %hh:%mm:%ss"); # 12.02.2013 16:16:53
168  
169 # DIG form
170 say fdt("%YYYY%MM%DD%hh%mm%ss"); # 20130212161844
171  
172 # HTTP headers format (See CGI::Util::expires)
173 say fdt("%w, %DD %MON %YYYY %hh:%mm:%ss %G", time, 1); # Tue, 12 Feb 2013 13:35:04 GMT
174  
175 # HTTP/cookie format (See CGI::Util::expires)
176 say fdt("%w, %DD-%MON-%YYYY %hh:%mm:%ss %G", time, 1); # Tue, 12-Feb-2013 13:35:04 GMT
177  
178 # COOKIE (RFC2616 as rfc1123-date)
179 say fdt("%w, %DD %MON %YYYY %hh:%mm:%ss %G", time, 1); # Tue, 12 Feb 2013 13:35:04 GMT
180  
181 For more features please use L<Date::Format>, L<DateTime> and L<POSIX/strftime>
182  
183 =head2 fduration
184  
185 print fduration( 123 );
186  
187 Returns formatted duration value
188  
189 =head2 humanize_duration
190  
191 print humanize_duration ( 123 );
192  
193 Turns duration value into a simplified human readable format
194  
195 =head2 humanize_number
196  
197 print humanize_number( $number, $sep );
198  
199 Placement of separators discharges among digits.
200 For example 1`234`567 if $sep is char "`" (default)
201  
202 =head2 human2bytes
203  
204 my $bytes = human2bytes("100 kB");
205  
206 Converts a human readable byte count into the pure number of bytes without any suffix
207  
208 See also L<Mojo::Util/humanize_bytes>
209  
210 =head2 indent
211  
212 my $indented = indent($str, 4, ' ');
213 my $indented = indent($str, 1, "\t");
214  
215 Indent multi-line string
216  
217 # " foo\n bar\n baz\n"
218 print indent("foo\nbar\nbaz\n", 2);
219  
220 You can use number of indent-chars and indent-symbol manuality:
221  
222 # "> foo\n> bar\n> baz\n"
223 my $data = indent("foo\nbar\nbaz\n", 1, '> ');
224  
225 See also L<Mojo::Util/unindent> to unindent multi-line strings
226  
227 =head2 is_os_type
228  
229 $is_windows = is_os_type('Windows');
230 $is_unix = is_os_type('Unix', 'dragonfly');
231  
232 Given an OS type and OS name, returns true or false if the OS name is of the given type.
233 As with os_type, it will use the current operating system as a default
234 if no OS name is provided
235  
236 Original this function see in L<Perl::OSType/is_os_type>
237  
238 =head2 load_class
239  
240 my $error = load_class('Foo::Bar');
241  
242 Loads a class and returns a false value if loading was successful,
243 a true value if the class was not found or loading failed.
244  
245 =head2 os_type
246  
247 $os_type = os_type(); # Unix
248 $os_type = os_type('MSWin32'); # Windows
249  
250 Returns a single, generic OS type for a given operating system name.
251 With no arguments, returns the OS type for the current value of $^O.
252 If the operating system is not recognized, the function will return the empty string.
253  
254 Original this function see in L<Perl::OSType/os_type>
255  
256 =head2 parse_expire
257  
258 print parse_expire("+1d"); # 86400
259 print parse_expire("-1d"); # -86400
260  
261 Returns offset of expires time (in secs).
262  
263 Original this function is the part of CGI::Util::expire_calc!
264  
265 This internal routine creates an expires time exactly some number of hours from the current time.
266 It incorporates modifications from Mark Fisher.
267  
268 format for time can be in any of the forms:
269  
270 now -- expire immediately
271 +180s -- in 180 seconds
272 +2m -- in 2 minutes
273 +12h -- in 12 hours
274 +1d -- in 1 day
275 +3M -- in 3 months
276 +2y -- in 2 years
277 -3m -- 3 minutes ago(!)
278  
279 If you don't supply one of these forms, we assume you are specifying the date yourself
280  
281 =head2 parse_time_offset
282  
283 my $off = parse_time_offset("1h2m24s"); # 4344
284 my $off = parse_time_offset("1h 2m 24s"); # 4344
285  
286 Returns offset of time (in secs)
287  
288 =head2 parse_words
289  
290 my $words = parse_words("foo,bar baz");
291 my $words = parse_words(@strings);
292 my $words = parse_words(\@strings);
293  
294 Parses one or more strings into a list of words.
295  
296 Input may be a single string, a list of strings or an array reference.
297 Words are separated by whitespace, commas and semicolons.
298  
299 Double-quoted strings are preserved as a single word, allowing separators
300 and whitespace to be embedded in a value.
301  
302 Empty tokens are discarded.
303  
304 Always returns an array reference.
305  
306 Examples:
307  
308 parse_words("foo,bar baz"); # [qw(foo bar baz)]
309 parse_words(["foo; bar", "baz qux"]);
310 # [qw(foo bar baz qux)]
311 parse_words(q{foo "bar baz" qux});
312 # ['foo', 'bar baz', 'qux']
313 parse_words([
314 q{foo,bar},
315 q{"baz qux"},
316 ]); # ['foo', 'bar', 'baz qux']
317  
318 See also L</words> for simply parsing
319  
320 =head2 prompt
321  
322 my $value = prompt($message);
323 my $value = prompt($message, $default);
324  
325 The C<prompt()> is an extremely simple function, based on the extremely simple prompt
326 offered by L<ExtUtils::MakeMaker>. In many cases this function just to prompt for input
327  
328 This function displays the message as a prompt for input and returns the (chomped)
329 response from the user, or the default if the response was empty
330  
331 If the program is not running interactively, the default will be used without prompting.
332 If no default is provided, an empty string will be used instead
333  
334 See also: L<ExtUtils::MakeMaker/prompt>, L<IO::Prompt::Tiny>
335  
336 =head2 randchars
337  
338 $rand = randchars( $n ); # default chars collection: 0..9,'a'..'z','A'..'Z'
339 $rand = randchars( $n, \@collection ); # Defined chars collection
340  
341 Returns random sequence of casual characters by the amount of n
342  
343 For example:
344  
345 $rand = randchars( 8, [qw/a b c d e f/]); # -> cdeccfdf
346  
347 =head2 slurp
348  
349 my $data = slurp($file, %args);
350 my $data = slurp($file, { %args });
351 slurp($file, { buffer => \my $data });
352 my $data = slurp($file, { binmode => ":raw:utf8" });
353  
354 Reads file $filename into a scalar
355  
356 my $data = slurp($file, { binmode => ":unix" });
357  
358 Reads file in fast, unbuffered, raw mode
359  
360 my $data = slurp($file, { binmode => ":unix:encoding(UTF-8)" });
361  
362 Reads file with UTF-8 encoding
363  
364 By default it returns this scalar. Can optionally take these named arguments:
365  
366 =over 4
367  
368 =item binmode
369  
370 Set the layers to read the file with. The default will be something sensible on your platform
371  
372 =item block_size
373  
374 Set the buffered block size in bytes, default to 1048576 bytes (1 MiB)
375  
376 =item buffer
377  
378 Pass a reference to a scalar to read the file into, instead of returning it by value.
379 This has performance benefits
380  
381 =back
382  
383 See also L</spew> to writing data to file
384  
385 =head2 spew
386  
387 spew($file, $data, %args);
388 spew($file, $data, { %args });
389 spew($file, \$data, { %args });
390 spew($file, \@data, { %args });
391 spew($file, $data, { binmode => ":raw:utf8" });
392  
393 Writes data to a file atomically. The only argument is C<binmode>, which is passed to
394 C<binmode()> on the handle used for writing.
395  
396 Can optionally take these named arguments:
397  
398 =over 4
399  
400 =item append
401  
402 This argument is a boolean option, defaulted to false (C<0>).
403 Setting this argument to true (C<1>) will cause the data to be be written at the end of the current file.
404 Internally this sets the sysopen mode flag C<O_APPEND>
405  
406 =item binmode
407  
408 Set the layers to write the file with. The default will be something sensible on your platform
409  
410 =item locked
411  
412 This argument is a boolean option, defaulted to false (C<0>).
413 Setting this argument to true (C<1>) will ensure an that existing file will not be overwritten
414  
415 =item mode
416  
417 This numeric argument sets the default mode of opening files to write.
418 By default this argument to C<(O_WRONLY | O_CREAT)>.
419 Please DO NOT set this argument unless really necessary!
420  
421 =item perms
422  
423 This argument sets the permissions of newly-created files.
424 This value is modified by your process's umask and defaults to 0666 (same as sysopen)
425  
426 =back
427  
428 See also L</slurp> to reading data from file
429  
430 =head2 spurt
431  
432 See L</spew>
433  
434 =head2 strf
435  
436 print strf( $format, %data );
437 print strf( $format, \%data );
438  
439 The C<strf> function returns a string representing hash-data as string in specified C<$format>.
440 This function is somewhat similar to the C function strftime(), except that the data source
441 is not the date and time, but the set of data passed to the function.
442  
443 The format string may be containing any combination of regular characters and special format
444 specifiers (patterns). These patterns are replaced to the corresponding values to represent
445 the data passed as second function argument. They all begin with a percentage (%) sign,
446 and are: '%c' or '%{word}'. The "c" is single character specifier like %d, the "word" is
447 regular word like "month" or "filename"
448  
449 If you give a pattern that doesn't exist, then it is simply treated as text.
450 If you give a pattern that doesn't defined but is exist in data set, then it will be
451 replaced to empty text string ('')
452  
453 B<Please note!> All patterns C<'%%'> will be replaced to literal C<'%'> character if you not
454 redefinet this pattern in Your data set manually
455  
456 Simple examples:
457  
458 my %d = (
459 f => 'foo',
460 b => 'bar',
461 baz => 'test',
462 u => undef,
463 t => time,
464 d => 1,
465 i => 2000,
466 n => "\n",
467 );
468  
469 print strf("test %f string", %d); # "test foo string"
470 print strf("%{baz} time=%t", %d); # "test time=1234567890"
471 print strf("test %f%b%i", %d); # "test foobar2000"
472 print strf("%d%% %{baz}", \%d); # "1% test"
473 print strf("%f%n%b", \%d); # "foo\nbar"
474 print strf("%f%u%b", \%d); # "foobar"
475 print strf("%f%X%b", \%d); # "foo%Xbar"
476  
477 =head2 touch
478  
479 touch( "file" ) or die "Can't touch file";
480  
481 Makes file exist, with current timestamp
482  
483 See L<ExtUtils::Command>
484  
485 =head2 trim
486  
487 print '"'.trim( " string " ).'"'; # "string"
488  
489 Returns the string with all leading and trailing whitespace removed.
490 Trim on undef returns undef. Original this function see String::Util
491  
492 =head2 truncstr
493  
494 print truncstr( $string, $cutoff_length, $continued_symbol );
495  
496 If the $string is longer than the $cutoff_length, then the string will be truncated
497 to $cutoff_length characters, including the $continued_symbol
498 (which defaults to '.' if none is specified).
499  
500 print truncstr( "qwertyuiop", 3, '.' ); # q.p
501 print truncstr( "qwertyuiop", 7, '.' ); # qw...op
502 print truncstr( "qwertyuiop", 7, '*' ); # qw***op
503  
504 Returns a line the fixed length from 3 to the n chars
505  
506 See also L<CTK::Util/variant_stf>
507  
508 =head2 tz_diff
509  
510 print tz_diff( time ); # +0300
511 print tz_diff( time, ':' ); # +03:00
512  
513 Returns TimeZone difference value
514  
515 print fdt("%w, %DD %MON %YYYY %hh:%mm:%ss ".tz_diff(time), time);
516  
517 Prints RFC-2822 format date
518  
519 =head2 words
520  
521 my $arr = words( ' foo bar, baz bar ' ); # ['foo', 'bar', 'baz']
522 my $arr = words( ' foo bar ', ' baz' ); # ['foo', 'bar', 'baz']
523 my $arr = words( [' foo bar ', ' baz'] ); # ['foo', 'bar', 'baz']
524 my $arr = words( ['foo, bar'], ['baz bar '] ); # ['foo', 'bar', 'baz']
525  
526 This function parse string by words and returns as an anonymous array.
527 All words in the resultating array are unique and arranged
528 in the order of the input string
529  
530 See also L</parse_words> for extended parsing
531  
532 =head1 HISTORY
533  
534 See C<Changes> file
535  
536 =head1 TO DO
537  
538 See C<TODO> file
539  
540 =head1 SEE ALSO
541  
542 L<Mojo::Util>
543  
544 =head1 AUTHOR
545  
546 Serż Minus (Sergey Lepenkov) L<https://www.serzik.com> E<lt>abalama@cpan.orgE<gt>
547  
548 =head1 COPYRIGHT
549  
550 Copyright (C) 1998-2026 D&D Corporation
551  
552 =head1 LICENSE
553  
554 This program is distributed under the terms of the Artistic License Version 2.0
555  
556 See the C<LICENSE> file or L<https://opensource.org/license/artistic-2-0> for details
557  
558 =cut
559  
560 5 ▶use Carp qw/ carp croak /;
Subroutine BEGIN: called CC=1 SCAR=0.0
561 5 ▶use IO::File qw//;
Subroutine BEGIN: called CC=1 SCAR=0.0
562 5 ▶use Term::ANSIColor qw/ colored /;
Subroutine BEGIN: called CC=1 SCAR=0.0
563 5 ▶use POSIX qw/ :fcntl_h ceil floor strftime /;
Subroutine BEGIN: called CC=1 SCAR=0.0
564 5 ▶use Fcntl qw/ O_WRONLY O_CREAT O_APPEND O_EXCL SEEK_END /;
Subroutine BEGIN: called CC=1 SCAR=0.0
565 5 ▶use Time::Local;
Subroutine BEGIN: called CC=1 SCAR=0.0
566 5 ▶use Data::Dumper qw//;
Subroutine BEGIN: called CC=1 SCAR=0.0
567 5 ▶use Storable qw/dclone/;
Subroutine BEGIN: called CC=1 SCAR=0.0
568 5 ▶use Text::ParseWords qw/quotewords/;
Subroutine BEGIN: called CC=1 SCAR=0.0
569  
570 5 ▶use Acrux::Const qw/ IS_TTY DATE_FORMAT DATETIME_FORMAT /;
Subroutine BEGIN: called CC=1 SCAR=0.0
571  
572 5 ▶use base qw/Exporter/;
Subroutine BEGIN: called CC=1 SCAR=0.0
573 5 our @EXPORT = (qw/
574 deprecated
575 dumper
576 clone
577 /);
578 5 our @EXPORT_OK = (qw/
579 fbytes human2bytes humanize_duration humanize_number
580 fdt dtf tz_diff fdate fdatetime fduration
581 randchars
582 dformat strf trim truncstr indent words
583 touch eqtime slurp spew spurt
584 parse_expire parse_time_offset parse_words
585 os_type is_os_type
586 color load_class
587 prompt
588 /, @EXPORT);
589  
590 5 ▶use constant HUMAN_SUFFIXES => {
Subroutine BEGIN: called CC=1 SCAR=0.0
591 'B' => 0,
592 'K' => 10, 'KB' => 10, 'KIB' => 10,
593 'M' => 20, 'MB' => 20, 'MIB' => 20,
594 'G' => 30, 'GB' => 30, 'GIB' => 30,
595 'T' => 40, 'TB' => 40, 'TIB' => 40,
596 'P' => 50, 'PB' => 50, 'PIB' => 50,
597 'E' => 60, 'EB' => 60, 'EIB' => 60,
598 'Z' => 70, 'ZB' => 70, 'ZIB' => 70,
599 'Y' => 80, 'YB' => 80, 'YIB' => 80,
600 5 };
601  
602 5 ▶use constant DTF => {
Subroutine BEGIN: called CC=1 SCAR=0.0
603 DOW => [qw/Sunday Monday Tuesday Wednesday Thursday Friday Saturday/],
604 DOWS => [qw/Sun Mon Tue Wed Thu Fri Sat/], # Short
605 MOY => [qw/January February March April May June July August September October November December/],
606 MOYS => [qw/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/], # Short
607 5 };
608  
609 # See Perl::OSType and Devel::CheckOS
610 5 my %OSTYPES = qw(
611 aix Unix
612 bsdos Unix
613 beos Unix
614 bitrig Unix
615 dgux Unix
616 dragonfly Unix
617 dynixptx Unix
618 freebsd Unix
619 linux Unix
620 haiku Unix
621 hpux Unix
622 iphoneos Unix
623 irix Unix
624 darwin Unix
625 machten Unix
626 midnightbsd Unix
627 minix Unix
628 mirbsd Unix
629 next Unix
630 openbsd Unix
631 netbsd Unix
632 dec_osf Unix
633 nto Unix
634 svr4 Unix
635 svr5 Unix
636 sco Unix
637 sco_sv Unix
638 unicos Unix
639 unicosmk Unix
640 solaris Unix
641 sunos Unix
642 cygwin Unix
643 msys Unix
644 os2 Unix
645 interix Unix
646 gnu Unix
647 gnukfreebsd Unix
648 nto Unix
649 qnx Unix
650 android Unix
651  
652 dos Windows
653 MSWin32 Windows
654  
655 os390 EBCDIC
656 os400 EBCDIC
657 posix-bc EBCDIC
658 vmesa EBCDIC
659  
660 MacOS MacOS
661 VMS VMS
662 vos VOS
663 riscos RiscOS
664 amigaos Amiga
665 mpeix MPEiX
666 );
667  
668  
669 # Common
670 0 ▶sub deprecated {
Subroutine deprecated: not called CC=2 SCAR=17.9
Pod documented
671 0 local $Carp::CarpLevel = 1;
672 0 ▶ $ENV{ACRUX_FATAL_DEPRECATIONS} ? croak @_ : carp @_;
Branch: 1 branch
BranchTrueFalseTotal
$ENV{'ACRUX_FATAL_DEPRECATIONS'} ? : 0 0 0
673 }
674 0 ▶sub dumper { Data::Dumper->new([@_])->Indent(1)->Sortkeys(1)->Terse(1)->Useqq(1)->Dump }
Subroutine dumper: not called CC=1 SCAR=6.9
Pod documented
675 1 ▶sub clone { dclone(shift) }
Subroutine clone: called CC=1 SCAR=0.0
Pod documented
676 0 ▶sub load_class {
Subroutine load_class: not called CC=6 SCAR=37.4
Pod documented
677 0 ▶ my $class = shift // '';
Condition0%0/2
shift() // ""
l!l
00
MC/DC0%0/1
shift() // ""
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
678 0 ▶ return "Invalid class name: $class" unless $class =~ /^\w(?:[\w:]*\w)?$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $class =~ /^\w(?:[\w:]*\w)?$/ 0 0 0
679 0 ▶ return undef if $class->can('new') || eval "require $class; 1"; # Ok
Branch: 1 branch
BranchTrueFalseTotal
if $class->can("new") or eval "require $class; 1" 0 0 0
Condition0%0/3
$class->can("new") or eval "require $class; 1"
l!l&&r!l&&!r
000
MC/DC0%0/2
$class->can("new") or eval "require $class; 1"
$class->can("new") eval "require $class; 1"
Truth table0%0/3
A or B
A= $class->can("new")B= eval "require $class; 1"
ABresult
1X1
011
000
680 0 ▶ return "Class $class not found" if $@ =~ /^Can't\s+locate/i; # Error
Branch: 1 branch
BranchTrueFalseTotal
if $@ =~ /^Can't\s+locate/i 0 0 0
681 0 return $@; # Error
682 }
683  
684 # Bytes and numbers
685 0 ▶sub fbytes {
Subroutine fbytes: not called CC=4 SCAR=30.0
Pod documented
686 0 my $n = int(shift);
687 0 ▶ if ($n >= 1024 ** 3) {
Branch: 3 branches
BranchTrueFalseTotal
if ($n >= 1073741824.0) { } 0 0 0
elsif ($n >= 1048576.0) { } 0 0 0
elsif ($n >= 1024) { } 0 0 0
688 0 return sprintf "%.3g GiB", $n / (1024 ** 3);
689 } elsif ($n >= 1024 ** 2) {
690 0 return sprintf "%.3g MiB", $n / (1024.0 * 1024);
691 } elsif ($n >= 1024) {
692 0 return sprintf "%.3g KiB", $n / 1024.0;
693 } else {
694 0 return "$n B"; # bytes
695 }
696 }
697 0 ▶sub human2bytes {
Subroutine human2bytes: not called CC=6 SCAR=37.4
Pod documented
698 0 ▶ my $h = shift || 0;
Condition0%0/2
shift() || 0
l!l
00
MC/DC0%0/1
shift() || 0
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
699 0 ▶ return 0 unless $h;
Branch: 1 branch
BranchTrueFalseTotal
unless $h 0 0 0
700 0 my ($bts, $sfx) = $h =~ /([0-9.]+)\s*([a-zA-Z]*)/;
701 0 ▶ return 0 unless $bts;
Branch: 1 branch
BranchTrueFalseTotal
unless $bts 0 0 0
702 0 ▶ my $exp = HUMAN_SUFFIXES->{($sfx ? uc($sfx) : "B")} || 0;
Branch: 1 branch
BranchTrueFalseTotal
$sfx ? : 0 0 0
Condition0%0/2
{B => 0, E => 60, EB => 60, EIB => 60, G => 30, GB => 30, GIB => 30, K => 10, KB => 10, KIB => 10, M => 20, MB => 20, MIB => 20, P => 50, PB => 50, PIB => 50, T => 40, TB => 40, TIB => 40, Y => 80, YB => 80, YIB => 80, Z => 70, ZB => 70, ZIB => 70}->{$sfx ? uc $sfx : 'B'} || 0
l!l
00
MC/DC0%0/1
{B => 0, E => 60, EB => 60, EIB => 60, G => 30, GB => 30, GIB => 30, K => 10, KB => 10, KIB => 10, M => 20, MB => 20, MIB => 20, P => 50, PB => 50, PIB => 50, T => 40, TB => 40, TIB => 40, Y => 80, YB => 80, YIB => 80, Z => 70, ZB => 70, ZIB => 70}->{$sfx ? uc $sfx : 'B'} || 0
{B => 0, E => 60, EB => 60, EIB => 60, G => 30, GB => 30, GIB => 30, K => 10, KB => 10, KIB => 10, M => 20, MB => 20, MIB => 20, P => 50, PB => 50, PIB => 50, T => 40, TB => 40, TIB => 40, Y => 80, YB => 80, YIB => 80, Z => 70, ZB => 70, ZIB => 70}->{$sfx ? uc $sfx : 'B'}
Truth table0%0/2
A
A= {B => 0, E => 60, EB => 60, EIB => 60, G => 30, GB => 30, GIB => 30, K => 10, KB => 10, KIB => 10, M => 20, MB => 20, MIB => 20, P => 50, PB => 50, PIB => 50, T => 40, TB => 40, TIB => 40, Y => 80, YB => 80, YIB => 80, Z => 70, ZB => 70, ZIB => 70}->{$sfx ? uc $sfx : 'B'}
Aresult
11
00
703 0 return ceil($bts * (2 ** $exp));
704 }
705 0 ▶sub humanize_duration {
Subroutine humanize_duration: not called CC=8 SCAR=42.8
Pod documented
706 0 ▶ my $msecs = shift || 0;
Condition0%0/2
shift() || 0
l!l
00
MC/DC0%0/1
shift() || 0
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
707 0 my $secs = int($msecs);
708 0 my $years = int($secs / (60*60*24*365));
709 0 $secs -= $years * 60*60*24*365;
710 0 my $days = int($secs / (60*60*24));
711 0 $secs -= $days * 60*60*24;
712 0 my $hours = int($secs / (60*60));
713 0 $secs -= $hours * 60*60;
714 0 my $mins = int($secs / 60);
715 0 $secs %= 60;
716 0 ▶ if ($years) { return sprintf("%d years %d days %s hours", $years, $days, $hours) }
Branch: 6 branches
BranchTrueFalseTotal
if ($years) { } 0 0 0
elsif ($days) { } 0 0 0
elsif ($hours) { } 0 0 0
elsif ($mins >= 2) { } 0 0 0
elsif ($secs > 5) { } 0 0 0
elsif ($msecs - $secs) { } 0 0 0
717 0 elsif ($days) { return sprintf("%d days %s hours %d minutes", $days, $hours, $mins) }
718 0 elsif ($hours) { return sprintf("%d hours %d minutes %d seconds", $hours, $mins, $secs) }
719 0 elsif ($mins >= 2) { return sprintf("%d minutes %d seconds", $mins, $secs) }
720 0 elsif ($secs > 5) { return sprintf("%d seconds", $secs + $mins * 60) }
721 0 elsif ($msecs - $secs) { return sprintf("%.4f seconds", $msecs) }
722 0 return sprintf("%d seconds", $secs);
723 }
724 0 ▶sub fduration {
Subroutine fduration: not called CC=5 SCAR=34.0
Pod documented
725 0 ▶ my $msecs = shift || 0;
Condition0%0/2
shift() || 0
l!l
00
MC/DC0%0/1
shift() || 0
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
726 0 my $secs = int($msecs);
727 0 my $hours = int($secs / (60*60));
728 0 $secs -= $hours * 60*60;
729 0 my $mins = int($secs / 60);
730 0 $secs %= 60;
731 0 ▶ if ($hours) {
Branch: 3 branches
BranchTrueFalseTotal
if ($hours) { } 0 0 0
elsif ($mins >= 2) { } 0 0 0
elsif ($secs < 120) { } 0 0 0
732 0 return sprintf("%d hours %d minutes", $hours, $mins);
733 } elsif ($mins >= 2) {
734 0 return sprintf("%d minutes", $mins);
735 } elsif ($secs < 2*60) {
736 0 return sprintf("%.4f seconds", $msecs);
737 } else {
738 0 $secs += $mins * 60;
739 0 return sprintf("%d seconds", $secs);
740 }
741 }
742 0 ▶sub humanize_number {
Subroutine humanize_number: not called CC=4 SCAR=30.0
Pod documented
743 0 ▶ my $var = shift || 0;
Condition0%0/2
shift() || 0
l!l
00
MC/DC0%0/1
shift() || 0
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
744 0 ▶ my $sep = shift || "`";
Condition0%0/2
shift() || '`'
l!l
00
MC/DC0%0/1
shift() || '`'
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
745 0 ▶ 1 while $var=~s/(\d)(\d\d\d)(?!\d)/$1$sep$2/;
Branch: 1 branch
BranchTrueFalseTotal
$var =~ s/(\d)(\d\d\d)(?!\d)/$1$sep$2/ and do { '???' } 0 0 0
746 0 return $var;
747 }
748  
749 # Date and Time utils
750 0 ▶sub fdate {
Subroutine fdate: not called CC=2 SCAR=17.9
Pod documented
751 0 ▶ my $t = shift || time;
Condition0%0/2
shift() || time
l!l
00
MC/DC0%0/1
shift() || time
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
752 0 return strftime(DATE_FORMAT, localtime($t));
753 }
754 1 ▶sub fdatetime {
Subroutine fdatetime: called CC=2 SCAR=7.2
Pod documented
755 1 ▶ my $t = shift || time;
Condition50%1/2
shift() || time
l!l
10
MC/DC0%0/1
shift() || time
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
756 1 return strftime(DATETIME_FORMAT, localtime($t));
757 }
758 0 ▶sub parse_expire {
Subroutine parse_expire: not called CC=7 SCAR=40.3
Pod documented
759 0 ▶ my $t = trim(shift(@_) // 0);
Condition0%0/2
shift @_ // 0
l!l
00
MC/DC0%0/1
shift @_ // 0
shift @_
Truth table0%0/2
A
A= shift @_
Aresult
11
00
760 0 my %mult = (
761 's' => 1,
762 'm' => 60,
763 'h' => 60*60,
764 'd' => 60*60*24,
765 'w' => 60*60*24*7,
766 'M' => 60*60*24*30,
767 'y' => 60*60*24*365
768 );
769 0 ▶ if (!$t || (lc($t) eq 'now')) {
Branch: 3 branches
BranchTrueFalseTotal
if (not $t or lc $t eq 'now') { } 0 0 0
elsif ($t =~ /^\d+$/) { } 0 0 0
elsif ($t =~ /^([+-]?(?:\d+|\d*\.\d*))([smhdwMy])/) { } 0 0 0
Condition0%0/3
not $t or lc $t eq "now"
l!l&&r!l&&!r
000
MC/DC0%0/2
not $t or lc $t eq "now"
not $t lc $t eq "now"
Truth table0%0/3
not(A) or B
A= not $tB= lc $t eq "now"
ABresult
1X1
011
000
770 0 return 0;
771 } elsif ($t =~ /^\d+$/) {
772 0 return $t; # secs
773 } elsif ($t=~/^([+-]?(?:\d+|\d*\.\d*))([smhdwMy])/) {
774 0 ▶ return ($mult{$2} || 1) * $1;
Condition0%0/2
$mult{$2} || 1
l!l
00
MC/DC0%0/1
$mult{$2} || 1
$mult{$2}
Truth table0%0/2
A
A= $mult{$2}
Aresult
11
00
775 }
776 0 return $t;
777 }
778 0 ▶sub parse_time_offset {
Subroutine parse_time_offset: not called CC=7 SCAR=40.3
Pod documented
779 0 ▶ my $s = trim(shift(@_) // 0);
Condition0%0/2
shift @_ // 0
l!l
00
MC/DC0%0/1
shift @_ // 0
shift @_
Truth table0%0/2
A
A= shift @_
Aresult
11
00
780 0 ▶ return $s if $s =~ /^\d+$/;
Branch: 1 branch
BranchTrueFalseTotal
if $s =~ /^\d+$/ 0 0 0
781 0 my $r = 0;
782 0 my $c = 0;
783 0 ▶ while ($s =~ s/([+-]?(?:\d+|\d*\.\d*)[smhdMy])//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s =~ s/([+-]?(?:\d+|\d*\.\d*)[smhdMy])//) 0 0 0
784 0 my $i = parse_expire("$1");
785 0 ▶ $c++ if $i < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $i < 0 0 0 0
786 0 ▶ $r += $i < 0 ? $i*-1 : $i;
Branch: 1 branch
BranchTrueFalseTotal
$i < 0 ? : 0 0 0
787 }
788 0 ▶ return $c ? $r*-1 : $r;
Branch: 1 branch
BranchTrueFalseTotal
$c ? : 0 0 0
789 }
790 0 ▶sub fdt {
Subroutine fdt: not called CC=21 SCAR=61.4
Pod documented
791 0 ▶ my $f = shift || ''; # Format
Condition0%0/2
shift() || ''
l!l
00
MC/DC0%0/1
shift() || ''
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
792 0 ▶ my $t = shift || time(); # Time
Condition0%0/2
shift() || time
l!l
00
MC/DC0%0/1
shift() || time
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
793 0 ▶ my $g = shift || 0; # 0 - Local time; 1 - GMT time
Condition0%0/2
shift() || 0
l!l
00
MC/DC0%0/1
shift() || 0
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
794  
795 0 my (@dt, %dth, %dth2);
796 0 ▶ @dt = $g ? gmtime($t) : localtime($t);
Branch: 1 branch
BranchTrueFalseTotal
$g ? : 0 0 0
797  
798 0 ▶ $dth{'%s'} = $dt[0] || 0;
Condition0%0/2
$dt[0] || 0
l!l
00
MC/DC0%0/1
$dt[0] || 0
$dt[0]
Truth table0%0/2
A
A= $dt[0]
Aresult
11
00
799 0 $dth{'%ss'} = sprintf('%02d',$dth{'%s'});
800 0 $dth{'%_s'} = sprintf('%2d',$dth{'%s'});
801 0 ▶ $dth{'%m'} = $dt[1] || 0;
Condition0%0/2
$dt[1] || 0
l!l
00
MC/DC0%0/1
$dt[1] || 0
$dt[1]
Truth table0%0/2
A
A= $dt[1]
Aresult
11
00
802 0 $dth{'%mm'} = sprintf('%02d',$dth{'%m'});
803 0 $dth{'%_m'} = sprintf('%2d',$dth{'%m'});
804 0 ▶ $dth{'%h'} = $dt[2] || 0;
Condition0%0/2
$dt[2] || 0
l!l
00
MC/DC0%0/1
$dt[2] || 0
$dt[2]
Truth table0%0/2
A
A= $dt[2]
Aresult
11
00
805 0 $dth{'%hh'} = sprintf('%02d',$dth{'%h'});
806 0 $dth{'%_h'} = sprintf('%2d',$dth{'%h'});
807 0 ▶ $dth{'%D'} = $dt[3] || 0;
Condition0%0/2
$dt[3] || 0
l!l
00
MC/DC0%0/1
$dt[3] || 0
$dt[3]
Truth table0%0/2
A
A= $dt[3]
Aresult
11
00
808 0 $dth{'%DD'} = sprintf('%02d',$dth{'%D'});
809 0 $dth{'%_D'} = sprintf('%2d',$dth{'%D'});
810 0 ▶ $dth{'%M'} = $dt[4] || 0; $dth{'%M'}++;
Condition0%0/2
$dt[4] || 0
l!l
00
MC/DC0%0/1
$dt[4] || 0
$dt[4]
Truth table0%0/2
A
A= $dt[4]
Aresult
11
00
811 0 $dth{'%MM'} = sprintf('%02d',$dth{'%M'});
812 0 $dth{'%_M'} = sprintf('%2d',$dth{'%M'});
813 0 ▶ $dth{'%Y'} = $dt[5] || 0; $dth{'%Y'}+=1900;
Condition0%0/2
$dt[5] || 0
l!l
00
MC/DC0%0/1
$dt[5] || 0
$dt[5]
Truth table0%0/2
A
A= $dt[5]
Aresult
11
00
814 0 $dth{'%YY'} = sprintf('%02d',$dth{'%Y'}%100);
815 0 $dth{'%YYY'} = sprintf('%03d',$dth{'%Y'}%1000);
816 0 $dth{'%YYYY'} = sprintf('%04d',$dth{'%Y'});
817 0 $dth{'%_Y'} = sprintf('%2d',$dth{'%Y'}%100);
818 0 $dth{'%_YY'} = sprintf('%3d',$dth{'%Y'}%1000);
819 0 ▶ $dth{'%w'} = DTF->{DOWS}->[$dt[6] || 0];
Condition0%0/2
$dt[6] || 0
l!l
00
MC/DC0%0/1
$dt[6] || 0
$dt[6]
Truth table0%0/2
A
A= $dt[6]
Aresult
11
00
820 0 ▶ $dth{'%W'} = DTF->{DOW}->[$dt[6] || 0];
Condition0%0/2
$dt[6] || 0
l!l
00
MC/DC0%0/1
$dt[6] || 0
$dt[6]
Truth table0%0/2
A
A= $dt[6]
Aresult
11
00
821 0 ▶ $dth{'%MON'} = DTF->{MOYS}->[$dt[4] || 0];
Condition0%0/2
$dt[4] || 0
l!l
00
MC/DC0%0/1
$dt[4] || 0
$dt[4]
Truth table0%0/2
A
A= $dt[4]
Aresult
11
00
822 0 ▶ $dth{'%mon'} = DTF->{MOYS}->[$dt[4] || 0];
Condition0%0/2
$dt[4] || 0
l!l
00
MC/DC0%0/1
$dt[4] || 0
$dt[4]
Truth table0%0/2
A
A= $dt[4]
Aresult
11
00
823 0 ▶ $dth{'%MONTH'} = DTF->{MOY}->[$dt[4] || 0];
Condition0%0/2
$dt[4] || 0
l!l
00
MC/DC0%0/1
$dt[4] || 0
$dt[4]
Truth table0%0/2
A
A= $dt[4]
Aresult
11
00
824 0 ▶ $dth{'%month'} = DTF->{MOY}->[$dt[4] || 0];
Condition0%0/2
$dt[4] || 0
l!l
00
MC/DC0%0/1
$dt[4] || 0
$dt[4]
Truth table0%0/2
A
A= $dt[4]
Aresult
11
00
825  
826 # Second block
827 0 ▶ $dth2{'%G'} = 'GMT' if $g;
Branch: 1 branch
BranchTrueFalseTotal
if $g 0 0 0
828 0 ▶ $dth2{'%U'} = 'UTC' if $g;
Branch: 1 branch
BranchTrueFalseTotal
if $g 0 0 0
829 0 $dth2{'%z'} = tz_diff($t, ':');
830 0 $dth2{'%Z'} = $dth2{'%z'}; $dth2{'%Z'} =~ s/\://;
831 0 $dth2{'%%'} = '%';
832  
833 0 $f =~ s/$_/$dth{$_}/sge for sort { length($b) <=> length($a) } keys %dth;
834 0 $f =~ s/$_/$dth2{$_}/sge for qw/%G %U %Z %z %%/;
835  
836 0 return $f
837 }
838 0 ▶sub dtf { goto &fdt }
Subroutine dtf: not called CC=1 SCAR=6.9
Pod documented
839 0 ▶sub tz_diff {
Subroutine tz_diff: not called CC=4 SCAR=30.0
Pod documented
840 0 ▶ my $tm = shift || time;
Condition0%0/2
shift() || time
l!l
00
MC/DC0%0/1
shift() || time
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
841 0 ▶ my $chr = shift // '';
Condition0%0/2
shift() // ""
l!l
00
MC/DC0%0/1
shift() // ""
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
842 0 my $diff = Time::Local::timegm(localtime($tm)) - Time::Local::timegm(gmtime($tm));
843 0 $diff = abs($diff);
844 0 ▶ my $direc = $diff < 0 ? '-' : '+';
Branch: 1 branch
BranchTrueFalseTotal
$diff < 0 ? : 0 0 0
845 0 my $tz_hr = int( $diff / 3600 );
846 0 my $tz_mi = int( $diff / 60 - $tz_hr * 60 );
847 0 return sprintf("%s%02d%s%02d", $direc, $tz_hr, $chr, $tz_mi);
848 }
849  
850 # Text utils
851 16 ▶sub trim {
Subroutine trim: called CC=2 SCAR=7.0
Pod documented
852 16 my $val = shift;
853 16 ▶ return unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 0 16 16
854 16 $val =~ s|^\s+||s; # trim left
855 16 $val =~ s|\s+$||s; # trim right
856 16 return $val;
857 }
858 0 ▶sub dformat { # Simple templating processor
Subroutine dformat: not called CC=4 SCAR=30.0
Pod documented
859 0 my $f = shift;
860 0 ▶ my $d = @_ ? @_ > 1 ? {@_} : {%{$_[0]}} : {};
Branch: 2 branches
BranchTrueFalseTotal
@_ ? : 0 0 0
@_ > 1 ? : 0 0 0
861 0 ▶ $f =~ s/\[([A-Z0-9_\-.]+?)\]/(defined($d->{$1}) ? $d->{$1} : "[$1]")/eg;
Branch: 1 branch
BranchTrueFalseTotal
defined $d->{$1} ? : 0 0 0
862 0 return $f;
863 }
864 0 ▶sub strf { # Yet another simple templating processor
Subroutine strf: not called CC=12 SCAR=50.5
Pod documented
865 0 ▶ my $s = shift // '';
Condition0%0/2
shift() // ""
l!l
00
MC/DC0%0/1
shift() // ""
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
866 0 ▶ my $h = @_ ? @_ > 1 ? {@_} : {%{$_[0]}} : {};
Branch: 2 branches
BranchTrueFalseTotal
@_ ? : 0 0 0
@_ > 1 ? : 0 0 0
867 0 ▶ return '' unless length $s;
Branch: 1 branch
BranchTrueFalseTotal
unless length $s 0 0 0
868 0 ▶ $h->{'%'} //= '%'; # by default '%' eq '%''
Condition0%0/2
$h->{"%"} //= "%"
l!l
00
MC/DC0%0/1
$h->{"%"} //= "%"
$h->{"%"}
Truth table0%0/2
A
A= $h->{"%"}
Aresult
11
00
869  
870 0 $s =~ s/
871 (?:
872 %\{(\w+)\} # short name like %{name}
873 |
874 %([%a-zA-Z]) # single character specifier like %d
875 )
876 /
877 ( $1
878 ? ( defined($h->{$1}) ? $h->{$1} : exists($h->{$1}) ? '' : "\%{$1}" )
879 : $2
880 0 ▶ ? ( defined($h->{$2}) ? $h->{$2} : exists($h->{$2}) ? '' : "\%$2" )
Branch: 6 branches
BranchTrueFalseTotal
$1 ? : 0 0 0
defined $h->{$1} ? : 0 0 0
exists $h->{$1} ? : 0 0 0
$2 ? : 0 0 0
defined $h->{$2} ? : 0 0 0
exists $h->{$2} ? : 0 0 0
881 : ''
882 )
883 /sgex;
884  
885 0 return $s;
886 }
887 0 ▶sub randchars {
Subroutine randchars: not called CC=6 SCAR=37.4
Pod documented
888 0 ▶ my $l = shift || return '';
Condition0%0/2
shift() || (return '')
l!l
00
MC/DC0%0/1
shift() || (return '')
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
889 0 ▶ return '' unless $l =~/^\d+$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $l =~ /^\d+$/ 0 0 0
890 0 my $arr = shift;
891 0 my $r = '';
892 0 ▶ my @chars = ($arr && ref($arr) eq 'ARRAY') ? (@$arr) : (0..9,'a'..'z','A'..'Z');
Branch: 1 branch
BranchTrueFalseTotal
$arr && ref $arr eq 'ARRAY' ? : 0 0 0
Condition0%0/3
$arr and ref $arr eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
$arr and ref $arr eq "ARRAY"
$arr ref $arr eq "ARRAY"
Truth table0%0/3
A and B
A= $arrB= ref $arr eq "ARRAY"
ABresult
0X0
100
111
893 0 $r .= $chars[(int(rand($#chars+1)))] for (1..$l);
894 0 return $r;
895 }
896 2 ▶sub truncstr {
Subroutine truncstr: called CC=7 SCAR=19.6
Pod documented
897 2 ▶ my $string = shift // '';
Condition50%1/2
shift() // ""
l!l
20
MC/DC0%0/1
shift() // ""
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
898 2 ▶ my $cutoff = shift || 0;
Condition50%1/2
shift() || 0
l!l
20
MC/DC0%0/1
shift() || 0
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
899 2 ▶ my $marker = shift // '.';
Condition100%2/2
shift() // "."
l!l
11
MC/DC100%1/1
shift() // "."
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
900  
901 # Get dots dumber
902 2 my $dots = 0;
903 2 ▶ $cutoff = 3 if $cutoff < 3;
Branch: 1 branch
BranchTrueFalseTotal
if $cutoff < 3 0 2 2
904 2 ▶ if ($cutoff < 6) { $dots = $cutoff - 2 }
Branch: 1 branch
BranchTrueFalseTotal
if ($cutoff < 6) { } 1 1 2
905 1 else { $dots = 3 }
906  
907 # Real length of cutted string
908 2 my $reallenght = $cutoff - $dots;
909  
910 # Input string is too short
911 2 ▶ return $string if length($string) <= $cutoff;
Branch: 1 branch
BranchTrueFalseTotal
if length $string <= $cutoff 0 2 2
912  
913 # Truncate
914 2 my $fix = floor($reallenght / 2);
915 2 my $new_start = substr($string, 0, ($reallenght - $fix)); # Start part of string
916 2 $new_start =~ s/\s+$//; # trim
917 2 my $new_midle = $marker x $dots; # Middle part of string
918 2 my $new_end = substr($string, (length($string) - $fix), $fix); # Last part of string
919 2 $new_end =~ s/^\s+//; # trim
920 2 return sprintf ("%s%s%s", $new_start, $new_midle, $new_end);
921 }
922 0 ▶sub indent {
Subroutine indent: not called CC=6 SCAR=37.4
Pod documented
923 0 ▶ my $str = shift // '';
Condition0%0/2
shift() // ""
l!l
00
MC/DC0%0/1
shift() // ""
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
924 0 ▶ my $ind = floor(shift || 0);
Condition0%0/2
shift() || 0
l!l
00
MC/DC0%0/1
shift() || 0
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
925 0 ▶ my $chr = shift // ' ';
Condition0%0/2
shift() // " "
l!l
00
MC/DC0%0/1
shift() // " "
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
926 0 ▶ return $str unless $ind && $ind <= 65535;
Branch: 1 branch
BranchTrueFalseTotal
unless $ind and $ind <= 65535 0 0 0
Condition0%0/3
$ind and $ind <= 65535
!ll&&!rl&&r
000
MC/DC0%0/2
$ind and $ind <= 65535
$ind $ind <= 65535
Truth table0%0/3
A and B
A= $indB= $ind <= 65535
ABresult
0X0
100
111
927 0 return join '', map { ($chr x $ind) . $_ . "\n" } split /\n/, $str;
928 }
929 10 ▶sub words {
Subroutine words: called CC=10 SCAR=23.1
Pod documented
930 10 my @in;
931 10 foreach my $r (@_) {
932 7 ▶ if (ref($r) eq 'ARRAY') { push @in, @$r } else { push @in, $r }
Branch: 1 branch
BranchTrueFalseTotal
if (ref $r eq 'ARRAY') { } 2 5 7
933 }
934 10 my %o;
935 10 my $i = 0;
936 10 foreach my $s (@in) {
937 9 ▶ $s = trim($s // '');
Condition50%1/2
$s // ""
l!l
90
MC/DC0%0/1
$s // ""
$s
Truth table50%1/2
A
A= $s
Aresult
11
00
938 9 ▶ next unless length($s) && !ref($s);
Branch: 1 branch
BranchTrueFalseTotal
unless length $s and not ref $s 2 7 9
Condition66%2/3
length $s and not ref $s
!ll&&!rl&&r
207
MC/DC50%1/2
length $s and not ref $s
length $s not ref $s
Truth table66%2/3
A and not(B)
A= length $sB= not ref $s
ABresult
0X0
100
111
939 7 foreach my $w (split(/[\s;,]+/, $s)) {
940 16 ▶ next unless length($w);
Branch: 1 branch
BranchTrueFalseTotal
unless length $w 0 16 16
941 16 ▶ $o{$w} = ++$i unless exists $o{$w};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $o{$w} 13 3 16
942 }
943 }
944 10 return [sort {$o{$a} <=> $o{$b}} keys %o ];
945 }
946  
947 # File utils
948 0 ▶sub touch {
Subroutine touch: not called CC=5 SCAR=34.0
Pod documented
949 0 ▶ my $fn = shift // '';
Condition0%0/2
shift() // ""
l!l
00
MC/DC0%0/1
shift() // ""
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
950 0 ▶ return 0 unless length($fn);
Branch: 1 branch
BranchTrueFalseTotal
unless length $fn 0 0 0
951 0 my $t = time;
952 0 my $ostat = open my $fh, '>>', $fn;
953 0 ▶ unless ($ostat) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ostat) 0 0 0
954 0 carp("Can't touch file \"$fn\": $!");
955 0 return 0;
956 }
957 0 ▶ close $fh if $ostat;
Branch: 1 branch
BranchTrueFalseTotal
if $ostat 0 0 0
958 0 utime($t, $t, $fn);
959 0 return 1;
960 }
961 0 ▶sub eqtime {
Subroutine eqtime: not called CC=8 SCAR=42.8
Pod documented
962 0 ▶ my $src = shift // '';
Condition0%0/2
shift() // ""
l!l
00
MC/DC0%0/1
shift() // ""
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
963 0 ▶ my $dst = shift // '';
Condition0%0/2
shift() // ""
l!l
00
MC/DC0%0/1
shift() // ""
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
964 0 ▶ return 0 unless length($src);
Branch: 1 branch
BranchTrueFalseTotal
unless length $src 0 0 0
965 0 ▶ return 0 unless length($dst);
Branch: 1 branch
BranchTrueFalseTotal
unless length $dst 0 0 0
966 0 ▶ unless ($src && -e $src) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($src and -e $src) 0 0 0
Condition0%0/3
$src and -e $src
!ll&&!rl&&r
000
MC/DC0%0/2
$src and -e $src
$src -e $src
Truth table0%0/3
A and B
A= $srcB= -e $src
ABresult
0X0
100
111
967 0 carp("Can't get access and modification times of file \"$src\": no file found");
968 0 return 0;
969 }
970 0 ▶ unless (utime((stat($src))[8,9], $dst)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (utime +(stat $src)[8, 9], $dst) 0 0 0
971 0 carp("Can't change access and modification times on file \"$dst\": $!");
972 0 return 0;
973 }
974 0 return 1;
975 }
976 0 ▶sub slurp {
Subroutine slurp: not called CC=16 SCAR=56.1
Pod documented
977 0 ▶ my $file = shift // '';
Condition0%0/2
shift() // ""
l!l
00
MC/DC0%0/1
shift() // ""
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
978 0 ▶ my $args = @_ ? @_ > 1 ? {@_} : {%{$_[0]}} : {};
Branch: 2 branches
BranchTrueFalseTotal
@_ ? : 0 0 0
@_ > 1 ? : 0 0 0
979 0 ▶ return unless length($file) && -r $file;
Branch: 1 branch
BranchTrueFalseTotal
unless length $file and -r $file 0 0 0
Condition0%0/3
length $file and -r $file
!ll&&!rl&&r
000
MC/DC0%0/2
length $file and -r $file
length $file -r $file
Truth table0%0/3
A and B
A= length $fileB= -r $file
ABresult
0X0
100
111
980 0 my $cleanup = 1;
981  
982 # Open filehandle
983 0 my $fh;
984 0 ▶ if (ref($file)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $file) { } 0 0 0
985 0 $fh = $file;
986 0 $cleanup = 0; # Disable closing filehandle for passed filehandle
987 } else {
988 0 $fh = IO::File->new($file, "r");
989 0 ▶ unless (defined $fh) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $fh) 0 0 0
990 0 carp qq/Can't open file "$file": $!/;
991 0 return;
992 }
993 }
994  
995 # Set binmode layer
996 0 ▶ my $bm = $args->{binmode} // ':raw'; # read in :raw by default
Condition0%0/2
$args->{"binmode"} // ":raw"
l!l
00
MC/DC0%0/1
$args->{"binmode"} // ":raw"
$args->{"binmode"}
Truth table0%0/2
A
A= $args->{"binmode"}
Aresult
11
00
997 0 $fh->binmode($bm);
998  
999 # Set buffer
1000 0 my $buf;
1001 0 ▶ my $buf_ref = $args->{buffer} // \$buf;
Condition0%0/2
$args->{"buffer"} // \$buf
l!l
00
MC/DC0%0/1
$args->{"buffer"} // \$buf
$args->{"buffer"}
Truth table0%0/2
A
A= $args->{"buffer"}
Aresult
11
00
1002 0 ${$buf_ref} = ''; # Set empty string to buffer
1003 0 ▶ my $blk_size = $args->{block_size} || 1024 * 1024; # Set block size (1 MiB)
Condition0%0/2
$args->{'block_size'} || 1048576
l!l
00
MC/DC0%0/1
$args->{'block_size'} || 1048576
$args->{'block_size'}
Truth table0%0/2
A
A= $args->{'block_size'}
Aresult
11
00
1004  
1005 # Read whole file
1006 0 my ($pos, $ret) = (0, 0);
1007 0 ▶ while ($ret = $fh->read(${$buf_ref}, $blk_size, $pos)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ret = $fh->read(${$buf_ref;}, $blk_size, $pos)) 0 0 0
1008 0 ▶ $pos += $ret if defined $ret;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ret 0 0 0
1009 }
1010 0 ▶ unless (defined $ret) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $ret) 0 0 0
1011 0 carp qq/Can't read from file "$file": $!/;
1012 0 return;
1013 }
1014  
1015 # Close filehandle
1016 0 ▶ $fh->close if $cleanup; # automatically closes the file
Branch: 1 branch
BranchTrueFalseTotal
if $cleanup 0 0 0
1017  
1018 # Return content if no buffer specified
1019 0 ▶ return if defined $args->{buffer};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"buffer"} 0 0 0
1020 0 return ${$buf_ref};
1021 }
1022 0 ▶sub spew {
Subroutine spew: not called CC=18 SCAR=58.3
Pod documented
1023 0 ▶ my $file = shift // '';
Condition0%0/2
shift() // ""
l!l
00
MC/DC0%0/1
shift() // ""
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
1024 0 ▶ my $data = shift // '';
Condition0%0/2
shift() // ""
l!l
00
MC/DC0%0/1
shift() // ""
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
1025 0 ▶ my $args = @_ ? @_ > 1 ? {@_} : {%{$_[0]}} : {};
Branch: 2 branches
BranchTrueFalseTotal
@_ ? : 0 0 0
@_ > 1 ? : 0 0 0
1026 0 my $cleanup = 1;
1027  
1028 # Get binmode layer, mode and perms
1029 0 ▶ my $bm = $args->{binmode} // ':raw'; # read in :raw by default
Condition0%0/2
$args->{"binmode"} // ":raw"
l!l
00
MC/DC0%0/1
$args->{"binmode"} // ":raw"
$args->{"binmode"}
Truth table0%0/2
A
A= $args->{"binmode"}
Aresult
11
00
1030 0 ▶ my $perms = $args->{perms} // 0666; # set file permissions
Condition0%0/2
$args->{"perms"} // 438
l!l
00
MC/DC0%0/1
$args->{"perms"} // 438
$args->{"perms"}
Truth table0%0/2
A
A= $args->{"perms"}
Aresult
11
00
1031 0 ▶ my $mode = $args->{mode} // O_WRONLY | O_CREAT;
Condition0%0/2
$args->{"mode"} // 65
l!l
00
MC/DC0%0/1
$args->{"mode"} // 65
$args->{"mode"}
Truth table0%0/2
A
A= $args->{"mode"}
Aresult
11
00
1032 0 ▶ $mode |= O_APPEND if $args->{append};
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"append"} 0 0 0
1033 0 ▶ $mode |= O_EXCL if $args->{locked};
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"locked"} 0 0 0
1034  
1035 # Open filehandle
1036 0 my $fh;
1037 0 ▶ if (ref($file)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $file) { } 0 0 0
1038 0 $fh = $file;
1039 0 $cleanup = 0; # Disable closing filehandle for passed filehandle
1040 } else {
1041 0 $fh = IO::File->new($file, $mode, $perms);
1042 0 ▶ unless (defined $fh) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $fh) 0 0 0
1043 0 carp qq/Can't open file "$file": $!/;
1044 0 return;
1045 }
1046 }
1047  
1048 # Set binmode layer
1049 0 $fh->binmode($bm);
1050  
1051 # Set buffer
1052 0 my $buf;
1053 0 my $buf_ref = \$buf;
1054 0 ▶ if (ref($data) eq 'SCALAR') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $data eq 'SCALAR') { } 0 0 0
elsif (ref $data eq 'ARRAY') { } 0 0 0
1055 0 $buf_ref = $data;
1056 } elsif (ref($data) eq 'ARRAY') {
1057 0 ${$buf_ref} = join '', @$data;
1058 } else {
1059 0 $buf_ref = \$data;
1060 }
1061  
1062 # Seek, print, truncate and close
1063 0 ▶ $fh->seek(0, SEEK_END) if $args->{append}; # SEEK_END == 2
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"append"} 0 0 0
1064 0 ▶ $fh->print(${$buf_ref}) or return;
Branch: 1 branch
BranchTrueFalseTotal
$fh->print(${$buf_ref;}) or return 0 0 0
1065 0 ▶ $fh->truncate($fh->tell) if $cleanup;
Branch: 1 branch
BranchTrueFalseTotal
if $cleanup 0 0 0
1066 0 ▶ $fh->close if $cleanup;
Branch: 1 branch
BranchTrueFalseTotal
if $cleanup 0 0 0
1067  
1068 0 return 1;
1069 }
1070 0 ▶sub spurt { goto &spew }
Subroutine spurt: not called CC=1 SCAR=6.9
Pod documented
1071  
1072 # Colored helper function
1073 0 ▶sub color {
Subroutine color: not called CC=4 SCAR=30.0
Pod documented
1074 0 my $clr = shift;
1075 0 ▶ my $txt = (scalar(@_) == 1) ? shift(@_) : sprintf(shift(@_), @_);
Branch: 1 branch
BranchTrueFalseTotal
scalar @_ == 1 ? : 0 0 0
1076 0 ▶ return $txt unless defined($clr) && length($clr);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $clr and length $clr 0 0 0
Condition0%0/3
defined $clr and length $clr
!ll&&!rl&&r
000
MC/DC0%0/2
defined $clr and length $clr
defined $clr length $clr
Truth table0%0/3
A and B
A= defined $clrB= length $clr
ABresult
0X0
100
111
1077 0 return IS_TTY ? colored([$clr], $txt) : $txt;
1078 }
1079  
1080 # Misc
1081 0 ▶sub os_type {
Subroutine os_type: not called CC=3 SCAR=24.8
Pod documented
1082 0 ▶ my $os = shift // $^O;
Condition0%0/3
shift() // $^O
l!l&&r!l&&!r
000
MC/DC0%0/2
shift() // $^O
shift() $^O
Truth table0%0/3
A // B
A= shift()B= $^O
ABresult
1X1
011
000
1083 0 ▶ return $OSTYPES{$os} || '';
Condition0%0/2
$OSTYPES{$os} || ''
l!l
00
MC/DC0%0/1
$OSTYPES{$os} || ''
$OSTYPES{$os}
Truth table0%0/2
A
A= $OSTYPES{$os}
Aresult
11
00
1084 }
1085 0 ▶sub is_os_type {
Subroutine is_os_type: not called CC=2 SCAR=17.9
Pod documented
1086 0 ▶ my $type = shift || return;
Condition0%0/2
shift() || (return)
l!l
00
MC/DC0%0/1
shift() || (return)
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
1087 0 return os_type(shift) eq $type;
1088 }
1089  
1090 # Copied from ExtUtils::MakeMaker and IO::Prompt::Tiny
1091 0 ▶sub prompt {
Subroutine prompt: not called CC=9 SCAR=45.0
Pod documented
1092 0 ▶ my $msg = shift // '';
Condition0%0/2
shift() // ""
l!l
00
MC/DC0%0/1
shift() // ""
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
1093 0 ▶ my $def = shift // '';
Condition0%0/2
shift() // ""
l!l
00
MC/DC0%0/1
shift() // ""
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
1094 0 ▶ my $dispdef = length($def) ? "[$def] " : " ";
Branch: 1 branch
BranchTrueFalseTotal
length $def ? : 0 0 0
1095  
1096 # Flush vars
1097 0 local $|=1;
1098 0 local $\;
1099  
1100 # Prompt message
1101 0 ▶ print length($msg) ? "$msg $dispdef" : "$dispdef";
Branch: 1 branch
BranchTrueFalseTotal
length $msg ? : 0 0 0
1102  
1103 0 my $ans;
1104 0 ▶ if (!IS_TTY && eof STDIN) {
Branch: 1 branch
BranchTrueFalseTotal
if (eof STDIN) { } 0 0 0
1105 0 print "$def\n";
1106 } else {
1107 0 $ans = <STDIN>;
1108 0 ▶ if( defined $ans ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ans) { } 0 0 0
1109 0 chomp $ans;
1110 } else { # user hit ctrl-D
1111 0 print "\n";
1112 }
1113 }
1114  
1115 0 ▶ return (!defined $ans || $ans eq '') ? $def : $ans;
Branch: 1 branch
BranchTrueFalseTotal
!defined($ans) || $ans eq '' ? : 0 0 0
Condition0%0/3
not defined $ans or $ans eq ""
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $ans or $ans eq ""
not defined $ans $ans eq ""
Truth table0%0/3
not(A) or B
A= not defined $ansB= $ans eq ""
ABresult
1X1
011
000
1116 }
1117  
1118 0 ▶sub parse_words {
Subroutine parse_words: not called CC=7 SCAR=40.3
Pod documented
1119 0 ▶ return [] unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 0 0 0
1120 0 ▶ my $in = @_
Branch: 3 branches
BranchTrueFalseTotal
@_ ? : 0 0 0
@_ > 1 ? : 0 0 0
ref $_[0] eq 'ARRAY' ? : 0 0 0
1121 ? @_ > 1
1122 ? [@_]
1123 : ref $_[0] eq 'ARRAY'
1124 ? $_[0]
1125 : [$_[0]]
1126 : [];
1127  
1128 0 my @w = ();
1129  
1130 0 foreach my $it (@$in) {
1131 0 ▶ push @w, grep { defined && length } quotewords(qr/\s+|[\,\;]+/, 0, $it);
Condition0%0/3
defined $_ && length $_
!ll&&!rl&&r
000
MC/DC0%0/2
defined $_ && length $_
defined $_ length $_
Truth table0%0/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
1132 }
1133  
1134 0 return [@w];
1135 }
1136  
1137 5 1;
1138  
1139 __END__
« Acme/Crux/Plugin/Log.pm ↑ Summary Acme/Crux.pm »