ePages 6.11.0 - DE_EPAGES/Core/API/PerlTools.pm

Package DE_EPAGES::Core::API::PerlTools

This Module collects useful function, which uses only standard or cpan modules. This Module initialize the randomizer via srand. Please dont call srand again !!!

@EXPORT_OK
fcmp
Compare
unique
string_unique
trim
isValid
GenerateGUID
GenerateShortGUID
ElementOf
Hex2Str
IndexOf
CopyStructure
GetDoubleHashFromLoop
GetLoopFromDoubleArray
GetCallerStack
GetCallerString
GetCallerPackage
GetCallerFunction
GetArchName
GetWindowsVersion
GetLocalTimeZone
GetLocalLocale
GetCurrentDateTime
AddDuration
SubtractDuration
GetIPAddress
GetIPAddresses
GetApplicationServerPort
SetApplicationServerPort
CreateNewPassWD
CryptPassword
CheckIpFormat
Ip2Hex
Str2Hex
Str2PerlStrDoubleQuote
Str2PerlStrSingleQuote
GetMD5Digest
UsePackage
UnloadPackage
IsA
Can

Functions

AddDuration
Can
CheckIpFormat
Compare
CopyStructure
CreateNewPassWD
CryptPassword
ElementOf
GenerateGUID
GenerateShortGUID
GetApplicationServerPort
GetArchName
GetCallerFunction
GetCallerPackage
GetCallerStack
GetCallerString
GetCurrentDateTime
GetDoubleHashFromLoop
GetIPAddress
GetIPAddresses
GetLocalLocale
GetLocalTimeZone
GetLoopFromDoubleArray
GetMD5Digest
GetWindowsVersion
Hex2Str
IndexOf
Ip2Hex
IsA
Str2Hex
Str2PerlStrDoubleQuote
Str2PerlStrSingleQuote
SubtractDuration
UnloadPackage
UsePackage
fcmp
isValid
string_unique
trim
unique

AddDuration

Adds a duration to a datetime object and returns the new one.

Syntax
$DateTime = AddDuration($OldDateTime, $DurationUnit, $Duration);
$example      $DateTime = AddDuration($OldDateTime, 'days', 1);
Input
$DateTime (DateTime object)
date time
$DurationUnit (string)
daration unit (minutes, hours, days, months, ...)
$Duration (integer)
daration value
Return
$DateTime (DateTime object)
date time after duration

Can

Provides a save way to check if a object has a method named $MethodName Should be used instead of UNIVERSAL->can().

Syntax
Can( $Object, $MethodName );
Input
$Object (object)
The object to check
$MethodName (string)
The name of the medthod
Return
$Ref (object)
Reference to the sub, undef if $Object does not have this method

CheckIpFormat

Tests if the parameter $IpAddress is an IP address of address family $AF.

Syntax
$ErrorMsg = CheckIpFormat($IpAddress);
$ErrorMsg = CheckIpFormat($IpAddress, $AF);
Example
$ErrorMsg = CheckIpFormat('123.120.34.254');
Input
$IpAddress (string)
parameter for test
$AF (number)
(optional) address family (4 or 6)
Output
$ErrorMsg (string)
error string

Compare

Different compares between a and b depending on the type of both elements. The parameter $Type can be ignored if both values are objects and have the method id().

Syntax
$result = Compare($Type, $a, $b);
Input
$Type (string)
String, LocalizedString, File, LocalizedFile, Money, Float, Boolean, Integer, DateTime (or a ClassName)
$a (*)
value 1
$b (*)
value 2
Return
$result (int)
0 if equal / -1 if smaller / 1 if greater

CopyStructure

Copies the full structure with objects, arrays, hashes, scalars but no code references using Data::Dumper.

Syntax
$Copy = CopyStructure($Structure);
Input
$Structure (ref.[^coderef]*)
structure to copy
Return
$Copy (ref.[^coderef]*)
copy

CreateNewPassWD

Generates a plain password containing only the characters 0..9a-zA-Z.

Syntax
$Password = CreateNewPassWD($UserName, $Length);
Input
$UserName (string)
unused
$Length (integer)
(optional, default=8) password length
Return
$Password (string)
generated password

CryptPassword

Generates a SHA-2 crypted password.

Syntax
$CryptedPassword = CryptPassword($Password, $Salt);
Input
$Password (string)
uncrypted passwd
$Salt (string)
old crypted passwd (optional and deprecated!)
Return
$CryptedPassword (string)
crypted passwd

ElementOf

Looks if an element is in the list (compare operator is 'eq' = string compare). Looks if an object is in the list (compares the ids of the object).

Syntax
$IsIncluded = ElementOf($Search, @List);
$IsIncluded = ElementOf($SearchObject, @ObjectList);
Input
$Search (string or object)
search word or search object
@List (array.string or array.object)
list of words or objects
Return
$IsIncluded (boolean)
search word or object was found in list

GenerateGUID

Returns 36-character long strings containing GUID (UUID). These look something like: b09e53f4-60e9-41a6-8b30-526b69c28b5d.

Syntax
$GUID = GenerateGUID();
Return
$GUID (string)
general unique identifier

GenerateShortGUID

returns a 20 char GUID which is shorter than the original 36 chars

Syntax
$ShortGUID = GenerateShortGUID();
Return
$GUID (string)
general unique identifier

GetApplicationServerPort

Returns the port of the application server.

Syntax
$ApplicationServerPort = GetApplicationServerPort();
Return
$ApplicationServerPort (integer)
as port 100043

GetArchName

Returns architecture name and 32 bit version of architecture name

Syntax
$ArchName = GetArchName();
Return
($ArchName, $ArchName32) (string)
architecture name, one of:
sun4-solaris
sun4-solaris64
i86pc-solaris
i86pc-solaris64
i586-linux
x86_64-linux
i586-MSWin32
x86_64-MSWin32

GetCallerFunction

Called by function. Get your own function name, get name of your caller function.

Syntax
$FunctionName = GetCallerFunction($SkipCallers);
Input
$SkipCallers (integer)
ingore first elements of stack (default 0)(optional)
Return
$FunctionName (string)
function name

GetCallerPackage

Called by package.

Syntax
$Package = GetCallerPackage($SkipCallers);
Input
$SkipCallers (integer)
ingore first elements of stack (default 0)(optional)
Return
$PackageName (string)
package name

GetCallerStack

Stack information. See additional information at "perldoc -f caller".

Syntax
$aaStack = GetCallerStack($SkipCallers);
Input
$SkipCallers (integer)
ingore first elements of stack (default 0)(optional)
Return
$aaStack (ref.array.array)
perl stack
  • 0 - means Package -package name - string
  • 1 - means FileName - file name - string
  • 2 - means Line - line number - integer
  • 3 - means SubName - function name - string
  • 4 - means HasArgs - has arguments (@_ is overwritten) - string
  • 5 - means WantArray - caller wants an array - string
  • 6 - means EvalText - text of the "eval EXPR" statement - string
  • 7 - means IsRequire - created by a "require" or "use" statement - boolean

GetCallerString

Returns a string representation of the caller stack.

Syntax
$CallerString = GetCallerString();
$CallerString = GetCallerString( $aaCallers);
$CallerString = GetCallerString( $aaCallers, $SkipCallers );
Example
$CallerString = GetCallerString( GetCallerStack() );
Input
$aaCallers (ref.array.hash)
caller double array, see GetCallerStack
$SkipCallers (integer)
ingore first elements of stack (default 0)(optional)
Return
$CallerString (string)
nicely formatted caller stack

GetCurrentDateTime

Returns the current time with server time_zone.

Syntax
$DateTime = GetCurrentDateTime();
Return
$DateTime (DateTime object)
current time

GetDoubleHashFromLoop

Converts a loop (array/hash) to a double hash (hash,hash). Neccesary is an identify field for the new key in the upper hash. Double entries are lost, eg: $hhDoubleHash->{$_->{$IdentKey}} = $_ foreach @$ahLoop.

Syntax
$hhDoubleHash = GetDoubleHashFromLoop($ahLoop, $IdentKey);
Input
$ahLoop (ref.array.hash.*)
loop
$IdentKey (string)
identifier for key (existing key of hashes in $ahLoop
Return
$hhDoubleHash (ref.hash.hash.*)
2 dimension hash

GetIPAddress

Returns the first IP address from $Address if multiple addresses are used. If address family $AF is omitted, 6 (IPv6) is used. If $Address is omitted, hostname() is used. The information is memorized until the program ends.

Syntax
$IPAddress = GetIPAddress();
$IPAddress = GetIPAddress($Address, $AF);
Input
$Address (string)
(optional) hostname or ip address
$AF (number)
(optional) address family: 4 (IPv4) or 6 (IPv6)
Return
$IPAddress (string)
IPv4/IPv6 address

GetIPAddresses

Returns a hash of all IP addresses for $Address (IP or hostname). If $Address is omitted, hostname() is used. The information is memorized until the program ends.

Syntax
$IpHash = GetIPAddresses($Address);
Input
$Address (string)
IPv4/IPv6 address or hostname
Return
(hash of IP address arrays with AF keys (4 or 6))
$IpHash

GetLocalLocale

Returns the local locale (germany 'de') DateTime::Locale of the application server machine. Under windows operating system returns the full name of languange and country (e.q. "German Germany") wh

Syntax
$locale = GetLocalLocale();
Return
$locale (string)
locale id (de_AT, en_GB)

GetLocalTimeZone

Returns the name of the server time zone. Uses the environment variables EPAGES_TZ or TZ.

Syntax
$timezone = GetLocalTimeZone();
Return
$timezone (string)
local time zone name (example: "Europe/Berlin")

GetLoopFromDoubleArray

Converts a 2 dimension array into a loop. The second array will be replaced by hash. Keys of hash are defined at second parameter.

Syntax
$ahLoop = GetLoopFromDoubleArray ($aaArray, $aKeys);
Input
$aaArray (ref.array.array.*)
2D array
$aKeys (array.string)
keys for inner hash
Return
$ahLoop (ref.array.hash.*)
2 dimension hash

GetMD5Digest

Returns the md5 hex digest of content

Syntax
$HexDigest = GetMD5Digest($rContent);
Example
my $HexDigest = GetMD5Digest(GetFileContent("/var/log/error.log"));
Input
$rContent (ref.string)
content of file
Return
$HexDigest (string)
md5 hex digest ( see perldoc Digest::MD5)

GetWindowsVersion

Returns Windows version name and number

Syntax
($VersionName, $VersionNumber) = GetWindowsVersion();
Return
($VersionName, $VersionNumber) (string)
number as 6.0.6001; name, list of:
Windows NT 3
Windows NT 4
Windows 95
Windows 98
Windows ME
Windows NT 5
Windows 2000
Windows XP
Windows .NET
Windows 2003
Windows Vista
Windows 2008
Windows 7

Hex2Str

Converts a hexadecimal code to a string.

Syntax
$String = Hex2Str(HexString);
Example
print Hex2Str('313241426162'); # prints '12ABab'
Input
$HexString (string)
hex representation of the string
Return
$String (string)
any string

IndexOf

Looks if an element is in the list (compare operator is 'eq' = string compare, if element is an object compares the ids of the object) and returns the posistion (0..) and -1 if not found.

Syntax
$Position = IndexOf($Search, @List);
$IsIncluded = ElementOf($SearchObject, @ObjectList);
Input
$Search (string or object)
search word or search object
@List (array.string or array.object)
list of words or objects
Return
$Position (integer)
position of search word

Ip2Hex

Returns the IP address as hex number.

Syntax
$IPHex = Ip2Hex($IP, $Length);
Example
Ip2Hex("1.2.3.4") -> 01020304;
Ip2Hex("1.2.3.4", 4) ->  0304;
Input
$IP (string)
IPv4 or IPv6 IP address string, e.g. 1.2.3.4
$Length
cut the hex number to $Length characters
Return
$IPAddress (string)
IPv4 or IPv6 address as hex number

IsA

Provides a save way to check if a $Object is blessed into package $ClassName or inherits from it. Should be used instead of UNIVERSAL->isa().

Syntax
IsA( $Object, $ClassName );
Input
$Object (object)
The object to check
$ClassName (string)
the name of the class
Return
$Result (boolean)
true if $Object is blessed into package $ClassName or inherits
from package $ClassName or false if not.

Str2Hex

Convers each byte in a string to a hexadecimal code.

Syntax
$Hex = Str2Hex($String);
Example
print Str2Hex('12ABab'); # prints '313241426162'
Input
$String (string)
any string
Return
$Hex (string)
hex representation of the string

Str2PerlStrDoubleQuote

Quotes the string that it can be used in a perl eval. The eval string includes a variable assignment with double quotes (see example).

Syntax
$OutString = Str2PerlStrDoubleQuote($InString);
Example
eval "\$Var1 = \"" . Str2PerlStrDoubleQuote('some string also @@$$ allowed') ."\";";
Input
$InString (string)
string the includes \\n"%$@
Return
$OutString (string)
quoted string

Str2PerlStrSingleQuote

Quotes the string that it can be used in a perl eval.The eval string includes a variable assignment with single quotes (see example).

Syntax
$OutString = Str2PerlStrSingleQuote($InString);
Example
eval "\$Var1 = '" . Str2PerlStrSingleQuote('some string also @@$$ allowed') ."';";
Input
$InString (string)
string the includes \\n"%$@
Return
$OutString (string)
quoted string

SubtractDuration

Subtracts a duration of a datetime object and returns the new one.

Syntax
$DateTime = SubtractDuration($OldDateTime, $DurationUnit, $Duration);
$example      $DateTime = SubtractDuration($OldDateTime, 'days', 1);
Input
$DateTime (DateTime object)
date time
$DurationUnit (string)
daration unit (minutes, hours, days, months, ...)
$Duration (integer)
daration value
Return
$DateTime (DateTime object)
date time after duration

UnloadPackage

Unloads a package to force it to be reloaded if needed next time. If a package name is invalid, this procedure dies with a proper message.

Syntax
UnloadPackage($PackageName);
Input
$PackageName (string)
package name

UsePackage

Provides a save way to load a package instead of utilizing 'eval "use $Package"' If $Package contains not a valid package name, this procedure dies with a proper message. Otherwise, the package is loaded.

Syntax
UsePackage($PackageName);
Input
$PackageName (string)
Name of the package to be loaded

fcmp

Compares two float numbers (avoid numeric problems, see example).

Syntax
$result = fcmp($Float1, $Float2, $Precision);
Example
my $a = 0.00011;
my $b = 1.10 - 1.09989;
printf "%d != %d\n", fcmp($a,$b), $a <=> $b;
Input
$Float1 (float)
first float number
$Float2 (float)
second float number
$Precision (int)
round to number of valid digits (optional 10)
Return
$result (int)
0 if pass / -1 if smaller / 1 if greater / undef if one is no float number

isValid

Is string defined and not empty ?

Syntax
$Valid = isValid($String);
Input
$String (string)
test string
Return
$Valid (boolean)
parameter is simple valid

string_unique

Removes duplicates from a list and preserves the sort order from the beginning. The string representation of each value "$Value" is used to find duplicates. Useful for strings but also for DateTime objects.

Syntax
@UniqueValues = string_unique @Values;
Example
print unique( "3", $a )
Input
@Values (array.*)
list of values with duplicates
Return
@UniqueValues (array)
list of unique values

trim

Removes leading and training whitespaces from a list of values.

Syntax
@TrimmedValues = trim @Values;
Example
print trim( "  A", " B", "\t   C\n" );
Input
@Values (array)
list of values with leading or trailing whitespace
Return
@TrimmedValues (array)
list of trimmed values

unique

Removes duplicates from a list and preserves the sort order from the beginning.

Syntax
@UniqueValues = unique @Values;
Example
print unique( 3,2,1,2,3 )
Input
@Values (array)
list of values with duplicates
Return
@UniqueValues (array)
list of unique values