Browsing TagPerl

Checking Regular Expression Syntax

If your program accepts a regular expression pattern, either from a user input or another module, you need to check that the pattern you receive is valid or not. To check for a valid pattern, apply the pattern against an empty string and wrap the expression in an eval.


sub my_func {
    my ($pattern) = @_;

    eval {
        "" =~ $pattern;
    };
    if ($@) {
        die "Something wrong with your pattern: $pattern";
    }

    # Otherwise, pattern is good and use it here.
}

How To Determine Installed Modules

Here’s how to determine what modules have been installed after the original Perl installation, hence showing those modules not part of the core installation. Type this from a command line:


perldoc perllocal

How To Tell A Number From A String

Often, I need to compare two variables but I don’t know if they are numbers or strings. I need to know the type so I can pick the proper comparison operators, i.e., == or eq, > or gt.
So, here’s how to do it:


~$x ne ~"$x" ? 'numeric' : 'string'

~ is the bitwise negation operator (see perlop). It does not negate integers and strings in the same way.

Examples:


$ perl -e 'print ~1, "n"'
4294967294
$ perl -e 'print ~"1", "n"'
Œ

(character which ASCII code is 255 – ord(‘1’))

Create Dir Path

To create a directory path programatically:


use File::Path;

mkpath "/usr/local/apache/htdocs/articles/2003";

This will create the 2003 directory and all parent directories as needed. This is the same as mkdir -p command.

Creating Timestamp

Several times I needed a timestamp for whatever reason. Here’s one that will return a scalar containing the current timestamp as in 03Jun19-114251.


sub create_timestamp {
    my ($sec, $min, $hour, $mday, $mon, $year) = localtime;
    my $month = (qw(Jan Feb Mar Apr May Jun
                    Jul Aug Sep Oct Nov Dec))[$mon];
    $year %= 100;

    my $timestamp = sprintf("%02d%s%02d-%02d%02d%02d",
                         $year, $month, $mday, $hour, $min, $sec);

    return $timestamp;
}