A Perl trim function

Perl string trim FAQ: Is there something like a "trim" function in Perl, similar to the Java trim function, which trims leading and trailing whitespace characters from a string?

A Perl trim function

My Perl skills aren't exactly up to date these days, but in days gone past there was no Perl trim function, and somewhere along the way I wrote one. Here's the source code for my Perl trim function:

# perl trim function - remove leading and trailing whitespace
sub trim($)
{
  my $string = shift;
  $string =~ s/^\s+//;
  $string =~ s/\s+$//;
  return $string;
}

This Perl trim function removes leading and trailing whitespace from an input string, and returns that results as a new string. Just include this trim function in your Perl script, and then use it something like this:

$new_string = trim($old_string);

Again, there may be newer ways to trim a string in Perl these days, but this Perl trim function has always worked for me.