NAME

Acrux::Util - The Acrux utilities

SYNOPSIS

use Acrux::Util;

DESCRIPTION

This module provides portable utility functions for Acrux

clone

my $copy = clone(\@array);
my $copy = clone(\%hash);

This function is a proxy function for "dclone" in Storable

It makes recursive copies of nested hash, array, scalar and reference types, including tied variables and objects. The clone() takes a scalar argument and duplicates it. To duplicate lists, arrays or hashes, pass them in by reference, e.g.

color

say color(blue => "Format %s %s" => "text", "foo");
say color(cyan => "text");
say color("red on_bright_yellow" => "text");
say STDERR color("red on_bright_yellow" => "text");

Returns colored formatted string if is session was runned from terminal

Supported normal foreground colors:

black, red, green, yellow, blue, magenta, cyan, white

Bright foreground colors:

bright_black, bright_red,     bright_green, bright_yellow
bright_blue,  bright_magenta, bright_cyan,  bright_white

Normal background colors:

on_black, on_red,     on_green, on yellow
on_blue,  on_magenta, on_cyan,  on_white

Bright background color:

on_bright_black, on_bright_red,     on_bright_green, on_bright_yellow
on_bright_blue,  on_bright_magenta, on_bright_cyan,  on_bright_white

See also Term::ANSIColor

deprecated

deprecated('foo is DEPRECATED in favor of bar');

Warn about deprecated feature from perspective of caller. You can also set the ACRUX_FATAL_DEPRECATIONS environment variable to make them die instead with Carp

dformat

$string = dformat( $mask, \%replacehash );
$string = dformat( $mask, %replacehash );

Replace substrings "[...]" in mask and returns replaced result. Data for replacing get from \%replacehash

For example:

# -> 01-foo-bar.baz.tgz
$string = dformat( "01-[NAME]-bar.[EXT].tgz", {
    NAME => 'foo',
    EXT  => 'baz',
});

See also "dformat" in CTK::Util

dtf

See "fdt"

dumper

my $perl = dumper({some => 'data'});

Dump a Perl data structure with Data::Dumper

eqtime

eqtime("from/file", "to/file") or die "Oops";

Sets modified time of destination to that of source

fbytes

print fbytes( 123456 );

Returns formatted size value

fdate

print fdate( time );

Returns formatted date value

fdatetime

print fdatetime( time );

Returns formatted date value

fdt

print fdt( $format, $time );
print fdt( $format, $time, 1 ); # in GMT context

Returns time in your format. Each conversion specification is replaced by appropriate characters as described in the following list

s, ss, _s - Seconds
m, mm, _m - Minutes
h, hh, _h - Hours
D, DD, _D - Day of month
M, MM, _M - Month
Y, YY, YYY, YYYY - Year
w       - Short form of week day (Sat, Tue and etc)
W       - Week day (Saturdat, Tuesday and etc)
MON, mon - Short form of month (Apr, May and etc)
MONTH, month - Month (April, May and etc)
Z       - Diff of TimeZone in short format (+0300)
z       - Diff of TimeZone in lomg format (+03:00)
G       - Short name of TimeZone GMT (for GMT context only)
U       - Short name of TimeZone UTC (for GMT context only)

Examples:

# RFC822 (RSS)
say fdt("%w, %D %MON %YY %hh:%mm:%ss %G", time(), 1); # Tue, 3 Sep 2013 12:31:40 GMT

# RFC850
say fdt("%W, %DD-%MON-%YY %hh:%mm:%ss %G", time(), 1); # Tuesday, 03-Sep-13 12:38:41 GMT

# RFC1036
say fdt("%w, %D %MON %YY %hh:%mm:%ss %G", time(), 1); # Tue, 3 Sep 13 12:44:08 GMT

# RFC1123
say fdt("%w, %D %MON %YYYY %hh:%mm:%ss %G", time(), 1); # Tue, 3 Sep 2013 12:50:42 GMT

# RFC2822
say fdt("%w, %DD %MON %YYYY %hh:%mm:%ss %Z"); # Tue, 12 Feb 2013 16:07:05 +0400
say fdt("%w, %DD %MON %YYYY %hh:%mm:%ss ".tz_diff());

# W3CDTF, ATOM (Same as RFC 3339/ISO 8601) -- Mail format
say fdt("%YYYY-%MM-%DDT%hh:%mm:%ss%z"); # 2013-02-12T16:10:28+04:00

# CTIME
say fdt("%w %MON %_D %hh:%mm:%ss %YYYY"); # Tue Feb  2 16:15:18 2013

# Russian date and time format
say fdt("%DD.%MM.%YYYY %hh:%mm:%ss"); # 12.02.2013 16:16:53

# DIG form
say fdt("%YYYY%MM%DD%hh%mm%ss"); # 20130212161844

# HTTP headers format (See CGI::Util::expires)
say fdt("%w, %DD %MON %YYYY %hh:%mm:%ss %G", time, 1); # Tue, 12 Feb 2013 13:35:04 GMT

# HTTP/cookie format (See CGI::Util::expires)
say fdt("%w, %DD-%MON-%YYYY %hh:%mm:%ss %G", time, 1); # Tue, 12-Feb-2013 13:35:04 GMT

# COOKIE (RFC2616 as rfc1123-date)
say fdt("%w, %DD %MON %YYYY %hh:%mm:%ss %G", time, 1); # Tue, 12 Feb 2013 13:35:04 GMT

For more features please use Date::Format, DateTime and "strftime" in POSIX

fduration

print fduration( 123 );

Returns formatted duration value

humanize_duration

print humanize_duration ( 123 );

Turns duration value into a simplified human readable format

humanize_number

print humanize_number( $number, $sep );

Placement of separators discharges among digits. For example 1`234`567 if $sep is char "`" (default)

human2bytes

my $bytes = human2bytes("100 kB");

Converts a human readable byte count into the pure number of bytes without any suffix

See also "humanize_bytes" in Mojo::Util

indent

my $indented = indent($str, 4, ' ');
my $indented = indent($str, 1, "\t");

Indent multi-line string

# "  foo\n  bar\n  baz\n"
print indent("foo\nbar\nbaz\n", 2);

You can use number of indent-chars and indent-symbol manuality:

# "> foo\n> bar\n> baz\n"
my $data = indent("foo\nbar\nbaz\n", 1, '> ');

See also "unindent" in Mojo::Util to unindent multi-line strings

is_os_type

$is_windows = is_os_type('Windows');
$is_unix    = is_os_type('Unix', 'dragonfly');

Given an OS type and OS name, returns true or false if the OS name is of the given type. As with os_type, it will use the current operating system as a default if no OS name is provided

Original this function see in "is_os_type" in Perl::OSType

load_class

my $error = load_class('Foo::Bar');

Loads a class and returns a false value if loading was successful, a true value if the class was not found or loading failed.

os_type

$os_type = os_type(); # Unix
$os_type = os_type('MSWin32'); # Windows

Returns a single, generic OS type for a given operating system name. With no arguments, returns the OS type for the current value of $^O. If the operating system is not recognized, the function will return the empty string.

Original this function see in "os_type" in Perl::OSType

parse_expire

print parse_expire("+1d"); # 86400
print parse_expire("-1d"); # -86400

Returns offset of expires time (in secs).

Original this function is the part of CGI::Util::expire_calc!

This internal routine creates an expires time exactly some number of hours from the current time. It incorporates modifications from Mark Fisher.

format for time can be in any of the forms:

now   -- expire immediately
+180s -- in 180 seconds
+2m   -- in 2 minutes
+12h  -- in 12 hours
+1d   -- in 1 day
+3M   -- in 3 months
+2y   -- in 2 years
-3m   -- 3 minutes ago(!)

If you don't supply one of these forms, we assume you are specifying the date yourself

parse_time_offset

my $off = parse_time_offset("1h2m24s"); # 4344
my $off = parse_time_offset("1h 2m 24s"); # 4344

Returns offset of time (in secs)

randchars

$rand = randchars( $n ); # default chars collection: 0..9,'a'..'z','A'..'Z'
$rand = randchars( $n, \@collection ); # Defined chars collection

Returns random sequence of casual characters by the amount of n

For example:

$rand = randchars( 8, [qw/a b c d e f/]); # -> cdeccfdf

slurp

my $data = slurp($file, %args);
my $data = slurp($file, { %args });
slurp($file, { buffer => \my $data });
my $data = slurp($file, { binmode => ":raw:utf8" });

Reads file $filename into a scalar

my $data = slurp($file, { binmode => ":unix" });

Reads file in fast, unbuffered, raw mode

my $data = slurp($file, { binmode => ":unix:encoding(UTF-8)" });

Reads file with UTF-8 encoding

By default it returns this scalar. Can optionally take these named arguments:

binmode

Set the layers to read the file with. The default will be something sensible on your platform

block_size

Set the buffered block size in bytes, default to 1048576 bytes (1 MiB)

buffer

Pass a reference to a scalar to read the file into, instead of returning it by value. This has performance benefits

See also "spew" to writing data to file

spew

spew($file, $data, %args);
spew($file, $data, { %args });
spew($file, \$data, { %args });
spew($file, \@data, { %args });
spew($file, $data, { binmode => ":raw:utf8" });

Writes data to a file atomically. The only argument is binmode, which is passed to binmode() on the handle used for writing.

Can optionally take these named arguments:

append

This argument is a boolean option, defaulted to false (0). Setting this argument to true (1) will cause the data to be be written at the end of the current file. Internally this sets the sysopen mode flag O_APPEND

binmode

Set the layers to write the file with. The default will be something sensible on your platform

locked

This argument is a boolean option, defaulted to false (0). Setting this argument to true (1) will ensure an that existing file will not be overwritten

mode

This numeric argument sets the default mode of opening files to write. By default this argument to (O_WRONLY | O_CREAT). Please DO NOT set this argument unless really necessary!

perms

This argument sets the permissions of newly-created files. This value is modified by your process's umask and defaults to 0666 (same as sysopen)

See also "slurp" to reading data from file

spurt

See "spew"

touch

touch( "file" ) or die "Can't touch file";

Makes file exist, with current timestamp

See ExtUtils::Command

trim

print '"'.trim( "    string " ).'"'; # "string"

Returns the string with all leading and trailing whitespace removed. Trim on undef returns undef. Original this function see String::Util

truncstr

print truncstr( $string, $cutoff_length, $continued_symbol );

If the $string is longer than the $cutoff_length, then the string will be truncated to $cutoff_length characters, including the $continued_symbol (which defaults to '.' if none is specified).

print truncstr( "qwertyuiop", 3, '.' ); # q.p
print truncstr( "qwertyuiop", 7, '.' ); # qw...op
print truncstr( "qwertyuiop", 7, '*' ); # qw***op

Returns a line the fixed length from 3 to the n chars

See also "variant_stf" in CTK::Util

tz_diff

print tz_diff( time ); # +0300
print tz_diff( time, ':' ); # +03:00

Returns TimeZone difference value

print fdt("%w, %DD %MON %YYYY %hh:%mm:%ss ".tz_diff(time), time);

Prints RFC-2822 format date

words

my $arr = words( ' foo bar,  baz bar ' ); # ['foo', 'bar', 'baz']
my $arr = words( ' foo bar ', '  baz' ); # ['foo', 'bar', 'baz']
my $arr = words( [' foo bar ', '  baz'] ); # ['foo', 'bar', 'baz']
my $arr = words( ['foo, bar'], ['baz bar '] ); # ['foo', 'bar', 'baz']

This function parse string by words and returns as an anonymous array. All words in the resultating array are unique and arranged in the order of the input string

HISTORY

See Changes file

TO DO

See TODO file

SEE ALSO

Mojo::Util

AUTHOR

Serż Minus (Sergey Lepenkov) https://www.serzik.com <abalama@cpan.org>

COPYRIGHT

Copyright (C) 1998-2024 D&D Corporation. All Rights Reserved

LICENSE

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

See LICENSE file and https://dev.perl.org/licenses/