up arrow Helpful Perl Functions

The following pair of functions are ones that I use often. As far as I’m concerned, they should be included in perl. This post serves as both a personal place holder and an opportunity to share with the Internets. Chances are you found them at the sweet end of a Google search.

Method: trim
Params: $string
Return:  $str
Usage:   $str = trim($str);

# This function trims white space from the
# front and back of parameter $string.
sub trim() {
  my $thing = shift;
  $thing =~ s/#.*$//; # trim trailing comments
  $thing =~ s/^\s+//; # trim leading whitespace
  $thing =~ s/\s+$//; # trim trailing whitespace
  return $thing;
}

 

Php offers a useful utility function called ‘empty’ which determines whether or not a variable is, well, empty. Here’s the equivalent function is perl:

Method: empty
Params: $string
Returns: boolean
Usage:    if (!empty($string)) { print “Whoo hoo!”; }

sub empty { ! defined $_[0] || ! length $_[0] }

 

I often use timestamps as unique identifiers or in transaction logging. The Internets are full of perl modules that provide timestamp functionality but I generally prefer to roll my own. Why? Mainly for portability. If a script relies on the basic perl library, then it runs on any server with perl installed.

Method: timestamp
Params: none
Returns: $string
Usage:    print timestamp() . “\n”;

# returns a string in the following format:
# YYYYMMDDHHMMSS
sub timestamp() {
  my $now   = time;
  my @date  = localtime $now;
  $date[5] += 1900;
  $date[4] += 1;
  my $stamp = sprintf(
    "%04d%02d%02d%02d%02d",
     $date[5],$date[4],$date[3], $date[2], $date[1], $date[0]
  );
  return $stamp;
}

NOTE: The above function was corrected to include seconds.
Posted in Perl, Programming | 1 Comment

One Response to “Helpful Perl Functions”

  1. Ajoy Bhatia says:

    Thanks for the PERL timestamp code, Jeff! Just one thing. According to the comment, timestamp() should also print out the seconds value but it does not. I changed it to:
    # returns a string in the following format:
    # YYYYMMDDHHMMSS
    sub timestamp() {
    my $now = time;
    my @date = localtime $now;
    $date[5] += 1900;
    $date[4] += 1;
    my $stamp = sprintf(
    “%04d-%02d-%02d %02d:%02d:%02d”,
    $date[5],$date[4],$date[3], $date[2], $date[1], $date[0]
    );
    return $stamp;
    }

    This prints the timestamp like this:
    2012-09-08 09:40:22

    Prints seconds, and just a little more readable.

Leave a Reply