Archive for Perl

Apr
16

How To Check If a Perl Module Exists

Posted by: | Comments (0)

To quickly check if a certain module is installed in your environment, do this from the command line

perl -MModuleName -e 1

If the prompt comes back with no message, then the module exists. Otherwise, if it comes back with a “Can’t Locate…” message, it’s not available.

Categories : Perl
Comments (0)
Apr
16

Cleanup Leading and Trailing Whitespaces

Posted by: | Comments (0)

Here’s a regular expression to remove the leading and trailing whitespaces from a string:


$str =~ s/^\s*//;    # remove leading whitespaces
$str =~ s/\s*$//;    # remove trailing whitespaces

I have often seen this used to do the same thing:


$str =~ s/\s*(.*?)\s*$/$1/;

According to the book Mastering Regular Expressions by Jeffrey E.F. Friedl, this is slower. The reason he says is that “with each character, before allowing the dot to match, the ‘*?’ must try to see whether what follows can match. That’s a lot of backtracking, particularly since it’s the kind that goes in and out of the parenthesis.”

Categories : Perl
Comments (0)
Apr
16

Output Logging Routine

Posted by: | Comments (0)

This code will allow logging into a file and optionally, to the screen as well. This will create the file if necessary.


sub mlog {
    my ($msg) = @_;
    open (FH, ">> /tmp/logfile.log")
        or croak "error opening logfile: $!\n";

    my $timestamp = localtime;
    print FH "$timestamp: $msg\n";
    close FH;

    print "$timestamp: $msg\n";    # also log to the screen
}

And to use this in your code:


mlog("This is a test log");
Categories : Perl
Comments (0)