Fork me on Github
Fork me on Github

Joe Dog Software

Proudly serving the Internets since 1999

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;
}
# Or use this function for perl 5.10 and higher
sub trim {                                                                                                              
  (my $s = $_[0]) =~ s/^\s+|\s+$//g;                                                                                    
  return $s;                                                                                                            
}                                                                                                                       

 

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.