Name

Class::Usul::Functions - Globally accessible functions

Synopsis

package MyBaseClass;

use Class::Usul::Functions qw( functions to import );

Description

Provides globally accessible functions

Subroutines/Methods

abs_path

$absolute_untainted_path = abs_path $some_path;

Untaints path. Makes it an absolute path and returns it. Returns undef otherwise. Traverses the filesystem

app_prefix

$prefix = app_prefix __PACKAGE__;

Takes a class name and returns it lower cased with :: changed to _, e.g. App::Munchies becomes app_munchies

arg_list

$args = arg_list @rest;

Returns a hash ref containing the passed parameter list. Enables methods to be called with either a list or a hash ref as it's input parameters

assert

assert $ioc_object, $condition, $message;

By default does nothing. Does not evaluate the passed parameters. The assert constant can be set via an inherited class attribute to do something useful with whatever parameters are passed to it

assert_directory

$untainted_path = assert_directory $path_to_directory;

Untaints directory path. Makes it an absolute path and returns it if it exists. Returns undef otherwise

base64_decode_ns

$decoded_value = base64_decode_ns $encoded_value;

Decode a scalar value encode using "base64_encode_ns"

base64_encode_ns

$encoded_value = base64_encode_ns $encoded_value;

Base 64 encode a scalar value using an output character set that preserves the input values sort order (natural sort)

bsonid

$bson_id = bsonid;

Generate a new BSON id. Returns a 24 character string of hex digits that are reasonably unique across hosts and are in ascending order. Use this to create unique ids for data streams like message queues and file feeds

bsonid_time

$seconds_elapsed_since_the_epoch = bsonid_time $bson_id;

Returns the time the BSON id was generated as Unix time

bson64id

$base64_encoded_extended_bson64_id = bson64id;

Like "bsonid" but better thread long running process support. A custom Base64 encoding is used to reduce the id length

bson64id_time

$seconds_elapsed_since_the_epoch = bson64id_time $bson64_id;

Returns the time the BSON64 id was generated as Unix time

canonicalise

$untainted_canonpath = canonicalise $base, $relpath;

Appends $relpath to $base using File::Spec::Functions. The $base and $relpath arguments can be an array reference or a scalar. The return path is untainted and canonicalised

class2appdir

$appdir = class2appdir __PACKAGE__;

Returns lower cased "distname", e.g. App::Munchies becomes app-munchies

classdir

$dir_path = classdir __PACKAGE__;

Returns the path (directory) of a given class. Like "classfile" but without the .pm extension

classfile

$file_path = classfile __PACKAGE__ ;

Returns the path (file name plus extension) of a given class. Uses File::Spec for portability, e.g. App::Munchies becomes App/Munchies.pm

create_token

$random_hex = create_token $optional_seed;

Create a random string token using "digest". If $seed is defined then add that to the digest, otherwise add some random data provided by a call to "urandom". Returns a hexadecimal string

create_token64

$random_base64 = create_token64 $optional_seed;

Like "create_token" but the output is base64 encoded

cwdp

$current_working_directory = cwdp;

Returns the current working directory, physical location

dash2under

$string_with_underscores = dash2under 'a-string-with-dashes';

Substitutes underscores for dashes

data_dumper

data_dumper $thing;

Uses Data::Printer to dump $thing in colour to stderr

digest

$digest_object = digest $seed;

Creates an instance of the first available Digest class and adds the seed. The constant DIGEST_ALGORITHMS is consulted for the list of algorithms to search for. Returns the digest object reference

distname

$distname = distname __PACKAGE__;

Takes a class name and returns it with :: changed to -, e.g. App::Munchies becomes App-Munchies

elapsed

$elapsed_seconds = elapsed;

Returns the number of seconds elapsed since the process started

emit

emit @lines_of_text;

Prints to STDOUT the lines of text passed to it. Lines are chomped and then have newlines appended. Throws on IO errors

emit_err

emit_err @lines_of_text;

Like "emit" but output to STDERR

emit_to

emit_to $filehandle, @lines_of_text;

Prints to the specified file handle

ensure_class_loaded

ensure_class_loaded $some_class, $options_ref;

Require the requested class, throw an error if it doesn't load

env_prefix

$prefix = env_prefix $class;

Returns upper cased app_prefix. Suitable as prefix for environment variables

escape_TT

$text = escape_TT '[% some_stash_key %]';

The left square bracket causes problems in some contexts. Substitute a less than symbol instead. Also replaces the right square bracket with greater than for balance. Template::Toolkit will work with these sequences too, so unescaping isn't absolutely necessary

exception

$e = exception $error;

Expose the catch method in the exception class Class::Usul::Exception. Returns a new error object

find_apphome

$directory_path = find_apphome $appclass, $homedir, $extns

Returns the path to the applications home directory. Searches the following:

# 0.  Pass the directory in (short circuit the search)
# 1a. Environment variable - for application directory
# 1b. Environment variable - for config file
# 2a. Users XDG_DATA_HOME env variable or XDG default share directory
# 2b. Users home directory - dot file containing shell env variable
# 2c. Users home directory - dot directory is apphome
# 3.  Well known path containing shell env file
# 4.  Default install prefix
# 5a. Config file found in @INC - underscore as separator
# 5b. Config file found in @INC - dash as separator
# 6.  Default to /tmp

find_source

$path = find_source $module_name;

Find absolute path to the source code for the given module

first_char

$single_char = first_char $some_string;

Returns the first character of $string

fqdn

$domain_name = fqdn $hostname;

Call gethostbyname on the supplied hostname whist defaults to this host

fullname

$fullname = fullname;

Returns the untainted first sub field from the gecos attribute of the object returned by a call to "get_user". Returns the null string if the gecos attribute value is false

get_cfgfiles

$paths = get_cfgfiles $appclass, $dirs, $extns

Returns an array ref of configurations file paths for the application

get_user

$user_object = get_user $optional_uid_or_name;

Returns the user object from a call to either getpwuid or getpwnam depending on whether an integer or a string was passed. The User::pwent package is loaded so objects are returned. On MSWin32 systems returns an instance of Class::Null. Defaults to the current uid but will lookup the supplied uid if provided

hex2str

$string = hex2str $pairs_of_hex_digits;

Converts the pairs of hex digits into a string of characters

home2appldir

$appldir = home2appldir $home_dir;

Strips the trailing lib/my_package from the supplied directory path

io

$io_object_ref = io $path_to_file_or_directory;

Returns a File::DataClass::IO object reference

is_arrayref

$bool = is_arrayref $scalar_variable

Tests to see if the scalar variable is an array ref

is_coderef

$bool = is_coderef $scalar_variable

Tests to see if the scalar variable is a code ref

is_hashref

$bool = is_hashref $scalar_variable

Tests to see if the scalar variable is a hash ref

is_member

$bool = is_member 'test_value', qw( a_value test_value b_value );

Tests to see if the first parameter is present in the list of remaining parameters

is_ntfs

$bool = is_ntfs;

Returns true if "is_win32" is true or the $OSNAME is cygwin

is_win32

$bool = is_win32;

Returns true if the $OSNAME is unfortunate

list_attr_of

$attribute_list = list_attr_of $object_ref, @exception_list;

Lists the attributes of the object reference, including defining class name, documentation, and current value

loginid

$loginid = loginid;

Returns the untainted name attribute of the object returned by a call to "get_user" or 'unknown' if the name attribute value is false

logname

$logname = logname;

Deprecated. Returns untainted the first true value returned by; the environment variable USER, the environment variable LOGNAME, and the function "loginid"

merge_attributes

$dest = merge_attributes $dest, $src, $defaults, $attr_list_ref;

Merges attribute hashes. The $dest hash is updated and returned. The $dest hash values take precedence over the $src hash values which take precedence over the $defaults hash values. The $src hash may be an object in which case its accessor methods are called

nonblocking_write_pipe_pair

$array_ref = non_blocking_write_pipe;

Returns a pair of file handles, read then write. The write file handle is non blocking, binmode is set on both

my_prefix

$prefix = my_prefix $PROGRAM_NAME;

Takes the basename of the supplied argument and returns the first _ (underscore) separated field. Supplies basename with extensions

ns_environment

$value = ns_environment $class, $key, $value;

An accessor / mutator for the environment variables prefixed by the supplied class name. Providing a value is optional, always returns the current value

pad

$padded_str = pad $unpadded_str, $wanted_length, $pad_char, $direction;

Pad a string out to the wanted length with the $pad_char which defaults to a space. Direction can be; both, left, or right and defaults to right

prefix2class

$class = prefix2class $PROGRAM_NAME;

Calls "my_prefix" with the supplied argument, splits the result on dash, ucfirsts the list and then joins that with ::

socket_pair

($reader, $writer) = @{ socket_pair };

Return a socketpair reader then writer. The writer has been closed on the reader and the reader has been closed on the writer

split_on__

$field = split_on__ $string, $field_no;

Splits string by _ (underscore) and returns the requested field. Defaults to field zero

split_on_dash

$field = split_on_dash $string, $field_no;

Splits string by - (dash) and returns the requested field. Defaults to field zero

squeeze

$string = squeeze $string_containing_muliple_spacesd;

Squeezes multiple whitespace down to a single space

strip_leader

$stripped = strip_leader 'my_program: Error message';

Strips the leading "program_name: whitespace" from the passed argument

sub_name

$sub_name = sub_name $level;

Returns the name of the method that calls it

$message = symlink $from, $to, $base;

It creates a symlink. If either $from or $to is a relative path then $base is prepended to make it absolute. Returns a message indicating success or throws an exception on failure

thread_id

$tid = thread_id;

Returns the id of this thread. Returns zero if threads are not loaded

throw

throw 'error_message', [ 'error_arg' ];

Expose "throw" in Class::Usul::Exception. Class::Usul::Constants has a class attribute Exception_Class which can be set change the class of the thrown exception

throw_on_error

throw_on_error @args;

Passes it's optional arguments to "exception" and if an exception object is returned it throws it. Returns undefined otherwise. If no arguments are passed "exception" will use the value of the global $EVAL_ERROR

trim

$trimmed_string = trim $string_with_leading_and_trailing_whitespace;

Remove leading and trailing whitespace including trailing newlines. Takes an additional string used as the character class to remove. Defaults to space and tab

unescape_TT

$text = unescape_TT '<% some_stash_key %>';

Do the reverse of escape_TT

untaint_cmdline

$untainted_cmdline = untaint_cmdline $maybe_tainted_cmdline;

Returns an untainted command line string. Calls "untaint_string" with the matching regex from Class::Usul::Constants

untaint_identifier

$untainted_identifier = untaint_identifier $maybe_tainted_identifier;

Returns an untainted identifier string. Calls "untaint_string" with the matching regex from Class::Usul::Constants

untaint_path

$untainted_path = untaint_path $maybe_tainted_path;

Returns an untainted file path. Calls "untaint_string" with the matching regex from Class::Usul::Constants

untaint_string

$untainted_string = untaint_string $regex, $maybe_tainted_string;

Returns an untainted string or throws

urandom

$bytes = urandom $optional_length, $optional_provider;

Returns random bytes. Length defaults to 64. The provider defaults to /dev/urandom and can be any type accepted by "io". If the provider exists and is readable, length bytes are read from it and returned. Otherwise some bytes from the second best generator are returned

uuid

$uuid = uuid $optional_uuid_proc_filesystem_path;

Return the contents of /proc/sys/kernel/random/uuid

whiten

$encoded = whiten 'plain_text_to_be_obfuscated';

Lifted from Acme::Bleach this function encodes the passed scalar as spaces, tabs, and newlines. The encrypt and decrypt functions take a seed attribute in their options hash reference. A whitened line of Perl code would be a suitable value

zip

%hash = zip @list_of_keys, @list_of_values;

Zips two list of equal size together to form a hash

chain

$result = chain $sub1, $sub2, $sub3

Call each sub in turn passing the returned value as the first argument to the next function call

compose

$code_ref = compose { }, $code_ref;

Returns a code reference which when called returns the result of calling the block passing in the result of calling the optional code reference. Delays the calling of the input code reference until the output code reference is called

curry

$curried_code_ref = curry $code_ref, @args;
$result = $curried_code_ref->( @more_args );

Returns a subroutine reference which when called, calls and returns the initial code reference passing in the original argument list and the arguments from the curried call. Must be called with a code reference and at least one argument

fold

*sum = fold { $a + $b } 0;

Classic reduce function with optional base value

Y

$code_ref = Y( $code_ref );

The Y-combinator function

factorial

$result = factorial $n;

Calculates the factorial for the supplied integer

fibonacci

$result = fibonacci $n;

Calculates the Fibonacci number for the supplied integer

product

$product = product 1, 2, 3, 4;

Returns the product of the list of numbers

sum

$total = sum 1, 2, 3, 4;

Adds the list of values

Diagnostics

None

Configuration and Environment

None

Dependencies

Class::Usul::Constants
Data::Printer
Digest
File::HomeDir
List::Util

Incompatibilities

The "home2appldir" method is dependent on the installation path containing a lib

The "uuid" method with only work on a OS with a /proc filesystem

Bugs and Limitations

There are no known bugs in this module. Please report problems to the address below. Patches are welcome

Author

Peter Flanigan, <pjfl@cpan.org>

License and Copyright

Copyright (c) 2016 Peter Flanigan. All rights reserved

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

This program is distributed in the hope that it will be useful, but WITHOUT WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE