Perlmazing - A collection of helper functions powered by Perlmazing::Engine.
SYNOPSIS
This module is the first practical example of a module powered by Perlmazing::Engine. It's a collection of helper functions that are loaded only when actually used, making it extremely fast to load and efficient to run. This manual will show you how to use this module and what its helper functions do, but you should look at Perlmazing::Engine to understand how it's being used and maybe look at the source code of this module to see how simple it was to implement Perlmazing::Engine for this example.
As an additional benefit, this module automatically use
s and import
s Perlmazing::Feature, which basically will enable strict
and warnings FATAL =
'all'>, along with the most recent features your version of Perl can enable.
How this module works at the end:
use Perlmazing;
# First of all, Perlmazing::Feature is automatically imported,
# so warnings and strict are automatically enabled and also
# any features that your version of Perl can have (similar to
# "use $]", if only that was a valid call).
# Now all helper functions are available. Yes, it exports
# all symbols by default. Please read the rest of this POD
# to understand why and when it's considered a good thing.
# Now use any of the helper functions from this module freely!
EXPORT
In the case of this module, all documented functions are exported by default, but that doesn't mean you have to work like that in your own module when using Perlmazing::Engine. It also doesn't mean that those functions are actually loaded into memory, they are just available to the caller and will be loaded and processed as soon as the caller actually calls one of them. Please read the documentation of Perlmazing::Engine to learn more about it.
FUNCTIONS
There are two types of functions in terms of behavior and this is something comming from Perlmazing::Engine. Basically, you get the regular type and the Listable
type. The regular type is simply any kind of subroutine, and it can simply do whatever you code it to do.
In the other hand, Listable
functions are all meant to have the same behavior as described in Perlmazing::Engine Listable functions and this should be warranted by Perlmazing::Engine's own code. These functions can, of course, do whatever you code them to do too, but they are all meant to follow this behavior:
# Assume 'my_sub' is a function of the type Listable:
# Calling my_sub on an array will directly affect elements of @array:
my_sub @array;
# Calling my_sub on a list will *attempt* to directly affect the
# elements of that list, failing on 'read only'/'constant' elements
# like the elements in the following list:
my_sub (1, 2, 3, 4, 5, 'string element');
# Calling my_sub on an array or a list BUT with an assignment,
# will *not* affect the original array or list, but assign an
# affected copy:
my @array_A = my_sub @array;
my @array_B = my_sub (1, 2, 3, 4, 5, 'string_element');
# Listable functions can be chained to achieve both behaviors
# (assignment or direct effect) on a single call. Assume
# 'my_sub2', 'my_sub3' and 'my_sub4' are also Listable functions:
my_sub my_sub1 my_sub2 my_sub3 my_sub4 @array;
my @array_C = my_sub my_sub1 my_sub2 my_sub3 my_sub4 (1, 2, 3, 4, 5, 'string element');
# When a Listable function is assigned in scalar context, then only the
# first element is assigned, not a list/array count.
my $scalar = my_sub @array; # $scalar contains the first element of the resulting list
In the following list of functions, each function will be documented by describing what it does and specifying Listable
functions, in which case you now know how you can use them to take advantage of that.
aes_decrypt
aes_decrypt($encrypted_data, $key)
Equivalent to MySQL's AES_DECRYPT function, 100% compatible with MySQL. Returns unencrypted data if successful.
aes_encrypt
aes_encrypt($plain_data, $key)
Equivalent to MySQL's AES_ENCRYPT function, 100% compatible with MySQL. Returns encrypted (binary) data.
carp
Same as Carp::carp().
cluck
Same as Carp::cluck().
copy
Same as File::Copy::Recursive::rcopy(). Copies a file using the native OS file-copy implementation. Not to be confused with Perl's link
, which doesn't create an actual copy. It will recursively copy directories when passed as argument.
croak
Same as Carp::croak().
cwd
Same as Cwd::cwd(). Returns the current working directory.
define
Listable function
Converts any undefined element into an empty string. Useful when purposely avoiding warnings on certain operations.
use strict;
use warnings;
my @array = (1, 2, 3, undef, undef, 6);
define @array;
# Now @array = (1, 2, 3, '', '', 6);
sub my_sub {
for my $i (define @_) {
# None of the following will cause an 'undefined' warning:
print "Received argument $i\n";
$i =~ s/\d//;
$i = 1 if $i eq 'abc';
}
}
dir
dir
dir($path)
dir($path, $recursive)
dir($path, $recursive, $callback)
This function will return an array with the contents of the directory given in $path
. If $path
is omited, then the current working directory is used. $recursive
is a boolean value, is optional and defaults to 0. When true, then the contents of subdirectories are returned too. $callback
is also optional and most be a coderef. If provided, then it will be called on each element found in real time. It receives the current element as argument.
dumped
Same as Data::Dump::dump(). It will return a code dump of whatever you provide as argument.
For example:
print dumped @array;
print dumped \@array; # Better
print dumped \%hash;
print dumped $some_object;
empty_dir
empty_dir($path)
This is almost the same as File::Path::remove_tree(), except it will make the folder privided in $path
empty without removing $path
too.
escape_html
Listable function
This function will html-escape any characters that are special to HTML. For example, it will replace &
with &
or <
with <
. It is a Listable function.
Examples:
print escape_html $some_text;
escape_html @array_A;
my @array_B = escape_html @array_C;
escape_uri
Listable function
This function will uri-escape any characters that are special to an URI. For example, it will replace &
with %26
or =
with %3D
. It is a Listable function.
Examples:
my $url = 'https://www.google.com.mx/search?q=';
my $query = escape_uri 'how are &, < and > escaped in html';
my $final_url = $url.$query;
my @escaped_queries = escape_uri @queries;
escape_uri @queries;
See also unescape_uri.
find_parent_classes
find_parent_classes($object)
This function will return an array containing all classes for which $object isa, in order of precedence. It basically walks through all namespaces found in its own @ISA
, and then recursively on each @ISA
for all found namespaces.
For example, the following code:
use Perlmazing;
use WWW::Mechanize;
my $mec = WWW::Mechanize->new;
my @classes = find_parent_classes $mec;
say for @classes;
will print something like:
WWW::Mechanize
LWP::UserAgent
LWP::MemberMixin
UNIVERSAL
get_time_from
get_time_from(year =
$year, month => $month, day => $day)>
Same as Time::Precise::get_time_from(). Returns time in seconds including nanoseconds.
gmtime
Same as Time::Precise::gmtime(). Returns time in seconds including nanoseconds.
gmtime_hashref
Same as Time::Precise::gmtime_hashref(). Returns a hashref with current datetime elements.
in_array
in_array(@array, $something_to_find)
This function will tell you if @array
contains an element identical to $something_to_find
. If found, it will return the index number for that element. For effective boolean effect, it will return the string 00
when the index is actually 0
. So, the following is a safe case:
my @array = ('first', 'second', 'third');
if (my $index = in_array @array, 'first') {
print "Found $array[$index]";
}
is_array
is_array($object)
Returns true if $object
is a pure arrayref. See also isa_array.
is_blessed
is_blessed($object)
Same as Scalar::Util::blessed(). Returns the name of the package $object
is a blessed into, if blessed.
is_code
is_code($object)
Returns true if $object
is a pure coderef. See also isa_code.
is_email_address
is_email_address($string)
Formed by a very complex, fast, RFC compliant regex that effectively validates any email address. Returns true is valid.
is_empty
is_empty($value)
Returns true if $value is equal en an empty string (''
) or $value is undefined.
is_filehandle
is_filehandle($value)
Returns true if $value is a valid filehandle.
is_format
is_format($object)
Returns true if $object
is a pure formatref. See also isa_format.
is_glob
is_glob($object)
Returns true if $object
is a pure globref. See also isa_glob.
is_hash
is_hash($object)
Returns true if $object
is a pure hashref. See also isa_hash.
is_io
is_io($object)
Returns true if $object
is a pure ioref. See also isa_io.
is_leap_year
is_leap_year($year)
Same as Time::Precise::is_leap_year(). Returns true if $year
is a leap year.
is_lvalue
is_lvalue($object)
Returns true if $object
is a pure lvalueref. See also isa_lvalue.
is_number
is_number($value)
Returns true if $value can be interpreted as a number. It is intended to work with any kind of expresion that Perl would take as a number if it was actual code, meaning that if it is a valid numeric expresion (whatever format) to Perl, then this function should return true too.
is_ref
is_ref($object)
Returns true if $object
is a pure refref. See also isa_ref.
is_regexp
is_regexp($object)
Returns true if $object
is a pure regexpref. See also isa_regexp.
is_scalar
is_scalar($object)
Returns true if $object
is a pure scalarref. See also isa_scalar.
is_utf8
is_utf8($string)
Returns true if $string
has valid UTF8 encodings. Basically, if Encode::decode('utf8', $str, Encode::FB_CROAK)
doesn't throw an error and only if the resulting value is different from $string, it will return true.
is_valid_date
is_valid_date($year, $month, $day)
Same as Time::Precise::is_valid_date(). Returns true if the values passed for $year
, $month
and $day
form together a valid date.
is_vstring
is_vstring($object)
Returns true if $object
is a pure vstringref. See also isa_vstring.
isa_array
isa_array($object)
Works just like is_array, except it will return true even if the reference is not pure (e.g. it's blessed into something).
isa_code
isa_code($object)
Works just like is_code, except it will return true even if the reference is not pure (e.g. it's blessed into something).
isa_format
isa_format($object)
Works just like is_format, except it will return true even if the reference is not pure (e.g. it's blessed into something).
isa_glob
isa_glob($object)
Works just like is_glob, except it will return true even if the reference is not pure (e.g. it's blessed into something).
isa_hash
isa_hash($object)
Works just like is_hash, except it will return true even if the reference is not pure (e.g. it's blessed into something).
isa_io
isa_io($object)
Works just like is_io, except it will return true even if the reference is not pure (e.g. it's blessed into something).
isa_lvalue
isa_lvalue($object)
Works just like is_lvalue, except it will return true even if the reference is not pure (e.g. it's blessed into something).
isa_ref
isa_ref($object)
Works just like is_ref, except it will return true even if the reference is not pure (e.g. it's blessed into something).
isa_regexp
isa_regexp($object)
Works just like is_regexp, except it will return true even if the reference is not pure (e.g. it's blessed into something).
isa_scalar
isa_scalar($object)
Works just like is_scalar, except it will return true even if the reference is not pure (e.g. it's blessed into something).
isa_vstring
isa_vstring($object)
Works just like is_vstring, except it will return true even if the reference is not pure (e.g. it's blessed into something).
list_context
list_context()
This function is meant to be called inside of a subroutine. It will return true if the subroutine was called in list context. See also void_context and scalar_context.
localtime
Same as Time::Precise::localtime(). Works as the core localtime
, except it returns nanoseconds and full year too.
longmess
Same as Carp::longmess().
md5
md5($value)
md5(@values)
my @result = md5(@values)
Listable function
This function returns the md5 representation (in hexadecimal) of the passed value(s). It will work as any other Listable function from this module.
md5_file
md5_file($path_to_file)
md5_file($file_handle)
This function will take a $path_to_file
or directly a $file_handle
, read the contents of the file in binary mode and return the md5 representation (in hexadecimal) of that file's contents.
merge
merge(%hash, key1 =
$value1, key2 => $value2, ...)>
This function is to a hash what push
is to an array. It will allow you to add as many keys as you want to an existing hash without having to create an splice or having to use the name of the hash for each assignment. If keys are repeated or existent, the last used one will be the one remaining. For example:
use Perlmazing;
my %hash = (
name => 'Francisco',
lastname => 'Zarabozo',
age => 'Unknown',
email => undef,
);
merge %hash, (
age => 20,
age => 30,
age => 40,
email => 'zarabozo@cpan.org',
gender => 'male',
pet => 'dog',
);
# Now %hash contains the following:
%hash = (
age => 40, # Last one used
email => 'zarabozo@cpan.org',
gender => 'male',
lastname => 'Zarabozo',
name => 'Francisco',
pet => 'dog',
);
mkdir
Works just like Perl's core mkdir
, except it will use File::Path::make_path() to create any missing directories in the requested path. It will return a list with the directories that were actually created.
move
Same as File::Copy::Recursive::rmove(). Moves a file using the native OS file-copy implementation. It will recursively move directories when passed as argument.
no_void
This function is meant to be called from inside a subroutine. The purpose of it is to break the execution of that subroutine and immediatly return with a warning if that subroutine was called in void context. This is useful when a certain function will do some time or memory consuming operations in order to return the result of those operations, which would be all for nothing if that function was called in void context. For example:
use Perlmazing;
# This will execute and will take a second to return
my $result = some_function();
say "Result is $result";
# Don't even bother, this will return immediatly without executing anything. Also a warning is issued:
# Useless call to main::some_function in void context at file.pl line 9.
some_function();
sub some_function {
no_void;
sleep 1; # Some time consuming operation;
return time;
}
not_empty
not_empty($var)
This is just an idiomatic way to test if a scalar value is something other than undef
or an empty string (''). It avoids warnings when using an undefined value in eq ''
. You would use it like this:
use Perlmazing;
my $values = {
undefined => undef,
empty => '',
filled => 'Hello!';
}
for my $key (keys %$values) {
if (not_empty $values->{$key}) {
say "Key $key conatins $values->{$key}";
}
}
# Only key 'filled' will get to say "Key filled contains Hello!"
numeric
sort numeric @something
This function is written to be used in conjuntion with sort
. It will sort values numerically when that's possible, numbers before strings and strings before undefined values. Example:
use Perlmazing;
my @values = qw(
3
8
2
0
1
3
7
5
bee
4
ark
9
code
6
20
10
123string
100
1000
1001
001000
);
@values = sort numeric @values;
# Now @values looks like this:
# 0, 1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 20, 100, 001000, 1000, 1001, 123string, ark, bee, code
# Without 'numeric' it would have been sorted like this:
# 0, 001000, 1, 10, 100, 1000, 1001, 123string, 2, 20, 3, 3, 4, 5, 6, 7, 8, 9, ark, bee, code
This sort order will also work for mixed cases between numeric and non-numeric cases. For example:
use Perlmazing;
my @values = qw(
book_1_page_3
book_1_page_1
book_1_page_2
book_1_page_03
book_1_page_01
book_1_page_02
book_01_page_3
book_01_page_1
book_01_page_2
book_10_page_3
book_10_page_3z
book_10_page_3a
book_10_page_3k
book_010_page_1
book_0010_page_2
);
@values = sort numeric @values;
# Now @values looks like this:
# book_01_page_1
# book_1_page_01
# book_1_page_1
# book_01_page_2
# book_1_page_02
# book_1_page_2
# book_01_page_3
# book_1_page_03
# book_1_page_3
# book_010_page_1
# book_0010_page_
# book_10_page_3
# book_10_page_3a
# book_10_page_3k
# book_10_page_3z
# Without 'numeric' it would have been sorted like this:
# book_0010_page_2
# book_010_page_1
# book_01_page_1
# book_01_page_2
# book_01_page_3
# book_10_page_3
# book_10_page_3a
# book_10_page_3k
# book_10_page_3z
# book_1_page_01
# book_1_page_02
# book_1_page_03
# book_1_page_1
# book_1_page_2
# book_1_page_3
pl
pl "something"
pl "more", "something else"
pl @anything
This function's name is short for "print lines". It was written way before core say
was announced and released. It was kept because it's not precisely the same as say
and I still find it much more useful.
It will print on separate lines everything that it receives as an argument - EXCEPT if you are assigning the return value of it to something else: in that case it will not print anything and will return a string containing what it would have printed. If assigning in list context, then an element for each line including a trailing "\n" on each one.
Examples:
use Perlmazing;
my @arr = (1..10);
pl "Hello world!";
# prints a "Hello world!" followed by a "\n"
pl @arr;
# Will print this:
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
my $r = pl @arr;
# Same, but it will ASSIGN to $r the output instead of printing it
my @r = pl @arr;
# An element in @r is created for each line that would be printed, including a trailing "\n" in each element
quotes_escape
quotes_escape($value)
quotes_escape(@values)
my @result = quotes_escape(@values)
Listable function
This is a very simple function that escapes with a backslash any match of the symbol "
. Works as any other listable function from this module.
quote_escape
Exactly the same as <quotes_escape|Perlmazing/quotes_escape>, except it escapes single quotes instead of double quotes.
remove_duplicates
remove_duplicates(@array)
A very useful function that will remove dumplicate entries from an array. The behavior and return value will be different according to whether it was called in void, scalar or list context. Look at these examples:
use Perlmazing;
my @values = qw(
1 2 3 4 5 6 7
3 4 5 6 7 8 9
5 6 7 8 9 10 11
3 4 5 6 7 8 9
1 2 3 4 5 6 7
);
# Try scalar context:
my $scalar = remove_duplicates @values;
# $scalar now contains the number of found duplicates (24) and nothing else is affected.
# Try list context:
my @list = remove_duplicates @values;
# Now @list contains a copy of @values WITHOUT duplicates (so it's now 1..11). @values remains untouched.
# Try void context:
remove_duplicates @values;
# You guessed. @values now has no duplicates (so it's now 1..11).
replace_accented_characters
replace_accented_characters($value)
replace_accented_characters(@values)
my @result = replace_accented_characters(@values)
Listable function
This function replaces any accented character (such as accented vowels in spanish) with it's closest representation in standard english alphabeth. For example, the character á
is replaced with a simple a
, or the character ü
is replaced with a simple u
. It works as any other listable function from this module.
rmdir
Works like core rmdir
, except it will remove the requested dir even if it's not empty.
scalar_context
This function is meant to be used from inside a subroutine. It will return true if the function was called in scalar context. Example:
use Perlmazing;
sub my_function {
my @array;
# do something with @array...
return $array[0] if scalar_context;
return @array;
}
shortmess
Same as Carp::shortmess().
shuffle
Same as List::Util::shuffle().
sleep
Same as core sleep
, except it will accept fractions and behave accordingly. Example:
use Perlmazing;
# Sleep a quarter of a second:
sleep 0.25;
# Sleep a second and a half:
sleep 1.5;
slurp
slurp($path_to_file, $force_binary_read)
This function will efficiently read and return the content of a file. Example:
use Perlmazing;
my $data = slurp 'some/file.txt';
It will use binmode on binary files only. If the second argument is a true value, then binmode will be used no matter what type of file is being read.
sort_by_key
sort_by_key(%hash)
sort_by_key($hashref)
This is a useful function that sorts its argument (a hash or a hashref) by key. The reason it's not a simple keyword like the case of numeric is the difficulty of knowing if core sort
is passing a key or a value in $a
and $b
.
This function will send a warning (and do nothing) if called in void context. The reason for this is that a regular hash cannot be sorted (or remain sorted after sorting it). Otherwise it will return a series of key-value pairs if called in list context, or an arrayref if called in scalar context. The following is an example of using it in list context:
use Perlmazing;
my @sorted = sort_by_key %ENV;
for (my $i = 0; $i < @sorted; $i += 2) {
say "$sorted[$i]: $sorted[$i + 1]";
}
sort_by_value
This is the same as the previously explained <sort_by_key|Perlmazing/sort_by_key> function, except it will sort its argument by value instead of by key.
taint
taint($value)
taint(@values)
my @result = taint(@values)
Listable function
Same as Taint::Util::taint() - except that it is a listable function and it will behave like any other listable function from this module.
tainted
Same as Taint::Util::tainted().
time
Same as core time
, except it will include decimals for nanoseconds.
time_hashref
time_hashref()
time_hashref($some_time_in_seconds)
This function will return a hashref the current local time if no argument is passed, or the time corresponding to its argument in seconds (e.g. the return value of core time()
).
The following is an example of a hashref returned by this function:
{
day => 16,
hour => 20,
is_leap_year => 1,
isdst => 0,
minute => 16,
month => "02",
second => "31.8393230",
wday => 2,
yday => 46,
year => 2016,
}
timegm
Same as Time::Local::timegm(), except it will include nanoseconds in its return value.
timelocal
Same as Time::Local::timelocal(), except it will include nanoseconds in its return value.
to_number
to_number($value)
to_number(@values)
my @result = to_number(@values)
Listable function
It makes any valid numeric value that is currently treated as string, a valid number. It works with any value that, if it wasn't treated as string, Perl would see as a number (e.g. 123_456), but that when treated as string, fails to to something like $value +=0. The value becomes a real numeric representation. It becomes zero when the value has no numeric interpretation. It is a listable function and will behave like any other listable function from this module.
to_string
to_string($value)
to_string(@values)
my @result = to_string(@values)
Listable function
It will simply treat any provided value as a string, making its last use to be seen as string by Perl (e.g. 123 will become "123"). Has no real effect on strings. It is a listable function and will behave like any other listable function from this module.
to_utf8
to_utf8($value)
to_utf8(@values)
my @result = to_utf8(@values)
Listable function
This is short for Encode::encode('utf8', $_[0]) if defined $_[0] and not is_utf8 $_[0]
, using Encode::encode(). It is a listable function and will behave like any other listable function from this module.
trim
trim($value)
trim(@values)
my @result = trim(@values)
Listable function
A very usefull function to remove any whitespace from the beginning or the ending of a string. It is a listable function (which makes it even more useful) and will act like any other listable function from this module. Example:
use Perlmazing;
my @lines = slurp $some_file;
trim @lines;
# Now each element of @lines is trimmed.
truncate_text
truncate_text($string, $length)
This is almost the same as substr($string, 0, $length)
, except this function will try not to cut words in the middle. Instead, it will look for the longest possible substring (according to $length
) where no word is cut in half. If that's not possible (e.g. there's no space between position 0 and $length
), then the string will be cut.
For example:
use Perlmazing;
my $string = 'This is an awesome string for testing.';
say truncate_text $string, 1;
# T
say truncate_text $string, 2;
# Th
say truncate_text $string, 3;
# Thi
say truncate_text $string, 4;
# This
say truncate_text $string, 5;
# This
say truncate_text $string, 6;
# This
say truncate_text $string, 7;
# This is
say truncate_text $string, 8;
# This is
say truncate_text $string, 9;
# This is
say truncate_text $string, 10;
# This is an
say truncate_text $string, 11;
# This is an
say truncate_text $string, 12;
# This is an
say truncate_text $string, 13;
# This is an
say truncate_text $string, 14;
# This is an
say truncate_text $string, 15;
# This is an
say truncate_text $string, 16;
# This is an
say truncate_text $string, 17;
# This is an
say truncate_text $string, 18;
# This is an awesome
# ...and so on.
unescape_html
unescape_html($value)
unescape_html(@values)
my @result = unescape_html(@values)
Listable function
This is the undo function for escape_html. It is a listable function and it will behave like any other listable function from this module.
unescape_uri
unescape_uri($value)
unescape_uri(@values)
my @result = unescape_uri(@values)
Listable function
This is the undo function for escape_uri. It is a listable function and it will behave like any other listable function from this module.
untaint
untaint($value)
untaint(@values)
my @result = untaint(@values)
Listable function
This is the undo function for taint. It is a listable function and it will behave like any other listable function from this module.
void_context
This function is meant to be called from inside a subroutine. It will return true if the function was called in void context. For example:
use Perlmazing;
# Will do nothing:
my_function();
# Will return '1':
my $r = my_function();
# Will return (1..10):
my @list = my_function();
sub my_function {
return if void_context; # Don't do anything if there's nothing using the return value
return 1 if scalar_context;
return (1..10) if list_context;
}
AUTHOR
Francisco Zarabozo, <zarabozo at cpan.org>
BUGS
Please report any bugs or feature requests to bug-perlmazing at rt.cpan.org
, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Perlmazing. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
SUPPORT
You can find documentation for this module with the perldoc command.
perldoc Perlmazing
You can also look for information at:
RT: CPAN's request tracker (report bugs here)
AnnoCPAN: Annotated CPAN documentation
CPAN Ratings
Search CPAN
LICENSE AND COPYRIGHT
Copyright 2015 Francisco Zarabozo.
This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License.
See http://dev.perl.org/licenses/ for more information.
2 POD Errors
The following errors were encountered while parsing the POD:
- Around line 54:
=pod directives shouldn't be over one line long! Ignoring all 2 lines of content
- Around line 902:
Non-ASCII character seen before =encoding in 'C<á>'. Assuming CP1252