Perl: function to trim string leading and trailing whitespace

Perl

Perl Problem Overview


Is there a built-in function to trim leading and trailing whitespace such that trim(" hello world ") eq "hello world"?

Perl Solutions


Solution 1 - Perl

Here's one approach using a regular expression:

$string =~ s/^\s+|\s+$//g ;     # remove both leading and trailing whitespace

Perl 6 will include a trim function:

$string .= trim;

Source: Wikipedia

Solution 2 - Perl

This is available in String::Util with the trim method:

Editor's note: String::Util is not a core module, but you can install it from CPAN with [sudo] cpan String::Util.

use String::Util 'trim';
my $str = "  hello  ";
$str = trim($str);
print "string is now: '$str'\n";

prints:

> string is now 'hello'

However it is easy enough to do yourself:

$str =~ s/^\s+//;
$str =~ s/\s+$//;

Solution 3 - Perl

There's no built-in trim function, but you can easily implement your own using a simple substitution:

sub trim {
    (my $s = $_[0]) =~ s/^\s+|\s+$//g;
    return $s;
}

or using non-destructive substitution in Perl 5.14 and later:

sub trim {
   return $_[0] =~ s/^\s+|\s+$//rg;
}

Solution 4 - Perl

According to this perlmonk's thread:

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

Solution 5 - Perl

Solution 6 - Perl

One option is Text::Trim:

use Text::Trim;
print trim("  example  ");

Solution 7 - Perl

For those that are using Text::CSV I found this thread and then noticed within the CSV module that you could strip it out via switch:

$csv = Text::CSV->new({allow_whitespace => 1});

The logic is backwards in that if you want to strip then you set to 1. Go figure. Hope this helps anyone.

Solution 8 - Perl

Apply: s/^\s*//; s/\s+$//; to it. Or use s/^\s+|\s+$//g if you want to be fancy.

Solution 9 - Perl

I also use a positive lookahead to trim repeating spaces inside the text:

s/^\s+|\s(?=\s)|\s+$//g

Solution 10 - Perl

No, but you can use the s/// substitution operator and the \s whitespace assertion to get the same result.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLandon KuhnView Question on Stackoverflow
Solution 1 - PerlMark ByersView Answer on Stackoverflow
Solution 2 - PerlEtherView Answer on Stackoverflow
Solution 3 - PerlEugene YarmashView Answer on Stackoverflow
Solution 4 - PerlbrettkellyView Answer on Stackoverflow
Solution 5 - PerlNanneView Answer on Stackoverflow
Solution 6 - PerlFlimmView Answer on Stackoverflow
Solution 7 - PerlDouglasView Answer on Stackoverflow
Solution 8 - PerlDirk-Willem van GulikView Answer on Stackoverflow
Solution 9 - PerlShaun McDonaldView Answer on Stackoverflow
Solution 10 - PerlPhilip PotterView Answer on Stackoverflow