CleanCode Perl Libraries
Multi-Lingual Library Maintainability
available: Perl not available: Java not available: JavaScript available: Certified
Class
not available: Testable
Class
not available: Standalone
Mode
not available: Diagnostic
Enabled

NAME

Data::Handy - Provides assorted data manipulation functions.

SYNOPSIS

    use Data::Handy;
    
        globifyArgv();
        interpolateArgv();
    
        return unless (promptYesNo("Keep processing"));
    
        $version = extractVersion("#Revision: 1.6 #"); 
        $packageName = fileToPkg("HTML/Foo.pm");
        $loadError = loadClass("HTML::Foo");
        $userPath = requireEnv("MY_PATH");
    
        if (isListMember(\@myList, $value)) { ... }
        print abbrJoin(", ", @list);
        $hashref = toHashMap(\@items,"key");
        $hashref = toHashSet(["a","b","c"]);
    
        $powerOfTwo = exponent(1024);
        $maxVal = max($a, $b);
        $minVal = min($a, $b);
    
        print hilight("sub-heading...", 80, '+');
        print hilightInline("test", 10);
        print commify(1234567);
        print commaKeys($hashRef);
        print bytesToString(1024);
        print makeVisible($x);
    
        if (($amount = dollarToNumber("($5.05)")) < 0) { ...
        print "Total = " . numberToDollar(-4.2);
        $val = nickelRound(12.53);
        $val = pennyRound(12.534);
    
        if (isArray($ref)) { ... }
        if (isHash($ref)) { ... }
        if (isObject($ref)) { ... }
        $vartype = typeof($somevar);
        if (isWindows()) { windows-specific action... }
    
        $newfile = replace($srcfile, ".shtml", ".html");
        $inputStr = interpolateText($inputStr);
    
        $stringMatch = escapeRegExp($s)

REQUIRES

Perl5.005, File::stat, Math::Round

EXPORTS

Default: none

Optional: abbrJoin, bytesToString, commify, commaKeys, deepCopy, dollarToNumber, exponent, extractVersion, fileToPkg, globifyArgv, hilight, hilightInline, interpolateArgv, interpolateText, isArray, isHash, isListMember, isObject, isWindows, loadClass, makeVisible, max, min, nickelRound, numberToDollar, pennyRound, promptYesNo, replace, requireEnv, toHashMap, toHashSet, typeof, escapeRegExp

DESCRIPTION

This is a general collection of data handling functions that are useful but not substantial enough to go into their own module.

FUNCTIONS

ARGV SUPPORT

interpolateArgv

interpolateArgv()

Modifies @ARGV in place, substituting certain control characters for their textual representations, allowing the user to supply them in text form on the command line. Characters modified: "\t" is replaced with a tab; "\n" is replaced with a newline. See also interpolateText.

globifyArgv

globifyArgv()

Modifies @ARGV in place, expanding any wildcards ("*" or "?"). Primarily useful in DOS, where command line wildcard arguments are not expanded by the shell, but must be done explicitly by each program.

INTERACTIVE SUPPORT

promptYesNo

promptYesNo(<promptString>)

Prompts the user on the console to provide a pause or allow a choice. Returns 1 if the user enters 'y' or 'yes', case-independent. The suffix " (y/n) ?" is attached to the prompt string (or the default).

Parameters:

promptString - optional; string; if not provided uses "Continue".

Returns:

Returns 1 if 'y' or 'yes' (case-independent); 0 otherwise.

PACKAGE AND VERSION SUPPORT

extractVersion

extractVersion(verString)

Extracts a canonical version number out of a version string (as from RCS, etc.). Each number is represented with at least 2 digits, except the first. So "V1.1" will return 1.01, etc.

Parameters:

verString - string containing version number

Returns:

Returns string representing the version number.

loadClass

loadClass(className)

Loads a class in a protected block, so failure will simply return a non-empty result, rather than causing any exceptions. The class must be locatable through your current Perl search path (via PERL5LIB or PERLLIB).

Parameters:

className - string specifying the name of the target class, e.g. Foo::Bar, which would load Foo/Bar.pm.

Returns:

Returns result of load operation, which is just the contents of $@. A non-empty value indicates some type of failure.

fileToPkg

fileToPkg(fileName)

Converts a file name to a package name, as in Foo/Bar.pm to Foo::Bar.

Parameters:

fileName - file name to convert

Returns:

Returns string containing class (package) name.

requireEnv

requireEnv(varName {, varName} )

Fetches the value of a specified environment variable; if not defined, an error message is sent to the console and the program aborted. One may optionally provide multiple variable names. In this case, the function will check each of them until it finds the first one that matches a defined environment variable. If it exhausts the whole list, then the behavior is the same as with a single name (error message and abort).

If the environment is Windows, one further action is performed: any backslashes are converted to forward slashes since both URL paths and Perl paths require forward slashes.

Parameters:

varName - required environment variable name

Returns:

Returns value of specified environment variable; aborts if not defined.

LIST SUPPORT

isListMember

isListMember(list, value, ignoreCase)

Determines if a value is a member of the supplied list.

Parameters:

list - list reference

value - value to check within list

ignoreCase - optional; boolean; if true, do case-independent check (default is false).

Returns:

1 if $value is a member of the list; 0 otherwise. An undefined or null value returns false (0).

abbrJoin

abbrJoin(separator, list)

Like the built-in join function, abbrJoin concatenates the members of a list into a string representation with separators. The result does not contain all elements of the list, but rather at most 3 elements.

Parameters:

separator - string to use as an element separator.

list - list from which to create an abbreviated string representation.

Returns:

String representation of abbreviated list.

toHashMap

toHashMap(listRef)

toHashMap(listRef, fieldName)

If a field name is supplied, toHashMap converts a list of hashes to a hash of hashes for ease of symbol lookup. That is, the specified field is promoted and duplicated as the new hash key. The list elements, then, must be hash references. This is useful when input data is supplied in "records" but you want it in a hash. For example, with

        $listRef = [
                {name=>"k1",val=>"v1",type=>"t3",count=>25},
                {name=>"k2",val=>"v2",type=>"t2",count=>93},
                {name=>"k3",val=>"v3",type=>"t1",count=>3}
        ];

then toHashMap($listRef, "name") returns

        {
                k1 => {name=>"k1",val=>"v1",type=>"t3",count=>25},
                k2 => {name=>"k2",val=>"v2",type=>"t2",count=>93},
                k3 => {name=>"k3",val=>"v3",type=>"t1",count=>3}
        }

If a field name is not supplied, then the result is practically trivial, simply turning the list reference into a hash reference. In this case the list elements which become keys must be scalars. Example:

        toHashMap(["key","k1","val","v1","key","k2","val","v2"]) =>
                { key=>"k1",val=>"v1",key=>"k2",val=>"v2" }
Parameters:

listRef - list of hash references or list of scalars

fieldName - optional; string; presence or absence determines behavior.

Returns:

Constructed hashMap reference.

toHashSet

toHashSet(listRef)

Converts a list of scalars to a set for ease of symbol lookup. The set is represented simply by a hash where each list element becomes a key; the corresponding value for each key is just set to 1 to indicate existence. Example:

        toHashSet(["a","b","c"]) => { "a"=>1, "b"=>1, "c"=>1 }
Parameters:

listRef - list of scalars

Returns:

Constructed hashSet reference.

MATH SUPPORT

exponent

exponent(value)

Calculates power of 2 which does not exceed the given value. So exponent(4) yields 2, exponent(7) still yields 2, but exponent(8) yields 3. For exact powers of 2, solves for x in 2^x = value. (Approximation to ((log($value)/log(2))+1) but faster... I think.)

Parameters:

value - integer

Returns:

Returns an integer between 0 and 31 inclusive (on 32-bit system).

min

min(a, b)

Find smaller of two numbers.

Parameters:

a - number

b - number

Returns:

Smaller of a or b.

max

max(a, b)

Find larger of two numbers.

Parameters:

a - number

b - number

Returns:

Larger of a or b.

DISPLAY SUPPORT

hilight

hilight(msg, len, borderChar)

hilight(msg, len)

hilight(msg)

hilight(title, msg, len, borderChar)

hilight(title, msg, len)

hilight(title, msg)

hilight(title)

Delimits a text block with a top and bottom border. The resultant string consists of a border, a line separator, the string, a border, and a line separator. If the string does not contain any line separators, one is inserted at the end, so that the bottom border starts at the beginning of a line. If the string contains a line separator, no additional one is added to its end.

Example: hilight("my list of stuff", 25, "+") yields

        +++++++++++++++++++++++++
        my list of stuff
        +++++++++++++++++++++++++

For added flexibility, you may also add a separate title as in this example:

Example: hilight("Category A", "my list of stuff", 25, "+") yields

        +++++++ Category A ++++++
        my list of stuff
        +++++++++++++++++++++++++
Parameters:

msg - string; message or title to delimit

len - optional; integer; length of each line. If omitted, defaults to 75.

borderChar - optional; character to use to generate the border. If omitted, defaults to "=".

title - optional; string to center within the top border bar itself

Returns:

Text block as a single string.

See also: hilightInline

hilightInline

hilightInline(msg, len, borderChar)

hilightInline(msg, len)

hilightInline(msg)

Adds border lines around text (for a single line of output). Example: hilight("my title", 25, "+") yields

        +++++++ my title ++++++++

Effectively a string of the borderChar characters is constructed of length len, then the msg is overlayed in the middle with a space on either side. If the msg itself is longer than the specified len, then just a single borderChar plus a space is added to both ends.

Parameters:

msg - string; message or title to delimit

len - optional; integer; total length of resultant string. If omitted, defaults to 75.

borderChar - optional; character to use to generate the border. If omitted, defaults to "=".

Returns:

hilighted string.

See also: hilight

commify

commify(number)

Returns the number with US-format commas inserted every 3 digits. If the number is floating point, then it will be formatted with two places to the right of the decimal point, since that typically will be an amount of currency. If the number is an integer, it is returned as an integer (with commas).

(Adapted from http://gossamer-threads.com/perl/gforum/gforum.cgi?post=62822.)

Parameters:

number - integer or float

Returns:

String representation with commas inserted

commaKeys

commaKeys(hashRef)

Returns the keys of the specified hash as a comma-separated string.

Parameters:

hashRef - reference to a hash

Returns:

String consisting of comma-separated hash keys.

bytesToString

bytesToString(size)

Returns size in a displayable format of bytes, kilobytes, or megabytes, as appropriate.

Parameters:

size - Non-negative value.

Returns:

String of "nnn" bytes or "nnn kb" or "nnn mb", depending on size.

makeVisible

makeVisible(item)

Normalize empty and undefined values for display purposes. This acts as a filter for any printable value. If the value is undefined, the string "(null)" will be returned. If the value is the empty string, the string "--" will be returned. Otherwise, the original value will be returned.

Parameters:

item - string; value to normalize

Returns:

normalized visible value

DOLLAR SUPPORT

dollarToNumber

dollarToNumber(amt)

Converts a monetary string to a number. Strips dollar sign, parentheses, and commas, if present, to convert the string representing a dollar figure into a raw number. The amt may or may not include any of these monetary characters: hyphen or parentheses to indicate a negative value, a dollar sign ($), a decimal point, and commas. Hence any of the following will return the relevant number (assuming "d" is any digit): $dd.dd, -.dd, -$dd, $dd,ddd.dd, and ($dd.dd). This function tries to be as forgiving as possible, so even a string such as "$101.45 / EA" will return a number. That is, the first possible run of contiguous monetary characters (specified above) will be parsed and returned.

Parameters:

amt - string representing a dollar amount

Returns:

Integer or floating point number; undef if no recognizable number.

numberToDollar

numberToDollar(number)

Converts the specified number to a dollar figure by rounding to the nearest penny, adding a dollar sign, and optionally adding parentheses if negative.

Parameters:

number - floating-point number representing a dollar amount.

Returns:

String, where negative amounts are represented with parentheses.

pennyRound

pennyRound(amt)

Rounds the amt to the nearest cent.

Parameters:

amt - floating-point number representing a dollar amount.

Returns:

Floating-point number rounded to the nearest hundredth.

nickelRound

nickelRound(amt)

Rounds the amt to the nearest nickel.

Parameters:

amt - floating-point number representing a dollar amount.

Returns:

Floating-point number rounded to the nearest five-hundredths.

REFLECTION SUPPORT

isArray

isArray(item)

Indicates whether the specified item is an array reference.

Parameters:

item - any scalar variable.

Returns:

Boolean indicating whether item is an array.

isHash

isHash(item)

Indicates whether the specified item is a hash reference.

Parameters:

item - any scalar variable.

Returns:

Boolean indicating whether item is a hash.

isObject

isObject(item)

Indicates whether the specified item is an object reference.

Parameters:

item - any scalar variable.

Returns:

Boolean indicating whether item is an object.

typeof

typeof(item)

Returns the type of the specified item. For non-objects, typeof returns the same as the builtin ref function. For objects, however, instead of the object's class, typeof returns the underlying data type.

Parameters:

item - any scalar variable.

Returns:

String representing the data type of the item.

isWindows

isWindows()

Indicates whether the operating system is a version of Windows.

Returns:

Boolean indicating whether the operating system is Windows.

deepCopy

deepCopy(any)

Makes a deep, rather than a shallow, copy of the argument. (Adapted from Deep copying, not Deep secrets by Randal Schwartz, stonehenge.com.)

Parameters:

any - any variable.

Returns:

Deep copy of the variable.

TEXT SUPPORT

replace

replace(source, pattern, substText)

Substitutes substText for pattern into a *copy* of the source text. This is merely a convenience function; it provides a function call look to the expression

        (my $text = $source) =~ s/$pattern/$substText/;

for ease of building expressions.

Parameters:

source - string; starting text to copy

pattern - string; regular expression to match in source

substText - string; replacement text to substitute for pattern

Returns:

String copy containing replaced text.

interpolateText

interpolateText(text)

Massages supplied string by converting text representation of tabs (\t) and newlines (\n) into actual tabs and newlines. Within Perl program text the conversion is done automatically in double-quoted strings, of course, but this is handy when text is read from a file or other sources. See also interpolateArgv.

Parameters:

text - string to process

Returns:

Updated string

escapeRegExp

escapeRegExp(string)

This method escapes regular expression meta-characters so that a string argument may be used literally in a regular expression. An example might be "snack(s)" where the parentheses are literal characters rather than denoting a regular expression group. The string would be changed to "snack\(s\)" to allow it to be used as a literal pattern.

Parameters:

s - string to escape

Returns:

Untainted string

BUGS

None

AUTHOR

Michael Sorens

VERSION

$Revision: 8 $ $Date: 2006-12-19 21:13:43 -0800 (Tue, 19 Dec 2006) $

SINCE

CleanCode 0.9

SEE ALSO

perl(1)

POD ERRORS

Hey! The above document had some coding errors, which are explained below:

Around line 1326:

=back doesn't take any parameters, but you said =back -- end of FUNCTION section


CleanCode Perl Libraries Copyright © 2001-2013 Michael Sorens - Revised 2013.06.30 Get CleanCode at SourceForge.net. Fast, secure and Free Open Source software downloads