CleanCode Perl Libraries |
Home | Perl | Java | PowerShell | C# | SQL | Index | Tools | Download | What's New |
Multi-Lingual Library | Maintainability | ||||||||||||
Perl | Java | JavaScript | Certified Class |
Testable Class |
Standalone Mode |
Diagnostic Enabled |
Data::Handy - Provides assorted data manipulation functions.
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)
Perl5.005, File::stat, Math::Round
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
This is a general collection of data handling functions that are useful but not substantial enough to go into their own module.
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()
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.
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).
promptString
- optional; string; if not provided uses "Continue".
Returns 1 if 'y' or 'yes' (case-independent); 0 otherwise.
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.
verString
- string containing version number
Returns string representing the version number.
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
).
className
- string specifying the name of the target class, e.g. Foo::Bar
, which would load Foo/Bar.pm
.
Returns result of load operation, which is just the contents of $@. A non-empty value indicates some type of failure.
fileToPkg(fileName)
Converts a file name to a package name, as in Foo/Bar.pm
to Foo::Bar
.
fileName
- file name to convert
Returns string containing class (package) name.
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.
varName
- required environment variable name
Returns value of specified environment variable; aborts if not defined.
isListMember(list, value, ignoreCase)
Determines if a value is a member of the supplied list.
list
- list reference
value
- value to check within list
ignoreCase
- optional; boolean; if true, do case-independent check (default is false).
1 if $value is a member of the list; 0 otherwise. An undefined or null value returns false (0).
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.
separator
- string to use as an element separator.
list
- list from which to create an abbreviated string representation.
String representation of abbreviated list.
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" }
listRef
- list of hash references or list of scalars
fieldName
- optional; string; presence or absence determines behavior.
Constructed hashMap reference.
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 }
listRef
- list of scalars
Constructed hashSet reference.
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.)
value
- integer
Returns an integer between 0 and 31 inclusive (on 32-bit system).
min(a, b)
Find smaller of two numbers.
a
- number
b
- number
Smaller of a or b.
max(a, b)
Find larger of two numbers.
a
- number
b
- number
Larger of a or b.
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
+++++++++++++++++++++++++
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
Text block as a single string.
See also: 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.
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 "=".
hilighted string.
See also: hilight
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.)
number
- integer or float
String representation with commas inserted
commaKeys(hashRef)
Returns the keys of the specified hash as a comma-separated string.
hashRef
- reference to a hash
String consisting of comma-separated hash keys.
bytesToString(size)
Returns size
in a displayable format of bytes, kilobytes, or megabytes, as appropriate.
size
- Non-negative value.
String of "nnn" bytes or "nnn kb" or "nnn mb", depending on size
.
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.
item
- string; value to normalize
normalized visible value
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.
amt
- string representing a dollar amount
Integer or floating point number; undef if no recognizable number.
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.
number
- floating-point number representing a dollar amount.
String, where negative amounts are represented with parentheses.
pennyRound(amt)
Rounds the amt to the nearest cent.
amt
- floating-point number representing a dollar amount.
Floating-point number rounded to the nearest hundredth.
nickelRound(amt)
Rounds the amt to the nearest nickel.
amt
- floating-point number representing a dollar amount.
Floating-point number rounded to the nearest five-hundredths.
isArray(item)
Indicates whether the specified item is an array reference.
item
- any scalar variable.
Boolean indicating whether item is an array.
isHash(item)
Indicates whether the specified item is a hash reference.
item
- any scalar variable.
Boolean indicating whether item is a hash.
isObject(item)
Indicates whether the specified item is an object reference.
item
- any scalar variable.
Boolean indicating whether item is an object.
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.
item
- any scalar variable.
String representing the data type of the item.
isWindows()
Indicates whether the operating system is a version of Windows.
Boolean indicating whether the operating system is Windows.
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.)
any
- any variable.
Deep copy of the variable.
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.
source
- string; starting text to copy
pattern
- string; regular expression to match in source
substText
- string; replacement text to substitute for pattern
String copy containing replaced text.
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.
text
- string to process
Updated string
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.
s
- string to escape
Untainted string
None
Michael Sorens
$Revision: 8 $ $Date: 2006-12-19 21:13:43 -0800 (Tue, 19 Dec 2006) $
CleanCode 0.9
perl(1)
Hey! The above document had some coding errors, which are explained below:
=back doesn't take any parameters, but you said =back -- end of FUNCTION section
Home | Perl | Java | PowerShell | C# | SQL | Index | Tools | Download | What's New |
CleanCode Perl Libraries | Copyright © 2001-2013 Michael Sorens - Revised 2013.06.30 |