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.

Permalink

Hmm.
Usually I do it like this:

$string =~ s/^\s+|\s+$//g;

Btw you have extra '$' character in "trim('old_string')"

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.