89

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

6
  • 4
    FYI: string equality in Perl is tested by the operator eq.
    – A. Rex
    Jan 4, 2011 at 20:16
  • 6
    A bit of clarification on all the asnwers you got: s/^\s+|\s+$//g; vs s/^\s*//; s/\s*$//; The latter is the (ever so slightly) more idiomatic way to do this, as starting the regex engine over is actually faster than the alternation, in this case. You can read more about this on Jeffrey Friedl's Mastering Regular Expressions. (Unless this was fixed in some newer version of Perl, in which case someone please correct me!)
    – Hugmeir
    Jan 4, 2011 at 20:30
  • 5
    Coming from a Java and .NET background, I'm almost shocked this isn't built into the language! THANKS ALL! Jan 4, 2011 at 20:50
  • 4
    @landon9720, it somewhat is: Scalar::Util has trim, and is core since 5.7.3 - That's 2002!
    – Hugmeir
    Jan 4, 2011 at 20:52
  • 4
    Hugmeir, this is wrong, see the answer of Ether.
    – daxim
    Jan 5, 2011 at 7:27

10 Answers 10

99

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

1
  • 7
    I look this up about once a month. Too bad I can't upvote it each time.
    – kyle
    Oct 29, 2014 at 19:31
87

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+$//;
6
  • 1
    @mklement0 nor will it ever be. But this is not relevant, since everyone should be using modules from the CPAN.
    – Ether
    Jun 9, 2015 at 21:12
  • 3
    why should everyone use modules from CPAN? It makes consistency difficult when using perl from your linux distribution (debian, redhat, ubuntu) combined with manually installed CPAN modules. It is much better if something can be done in perl using modules which are available as packages in linux distribution
    – Marki555
    Jan 11, 2016 at 10:01
  • 1
    @Marki555 modules available as packages in your linux distro are from CPAN -- they've just been repackaged. You can generally request a certain module to be packaged if it hasn't been done so already (the debian folks are particularly responsive and helpful).
    – Ether
    Jan 12, 2016 at 18:57
  • 3
    I know they are also from CPAN... Yes, generally I can request a new pkg for debian, but it won't help me for my installed debian stable release... that's why I prefer packages modules, but use directly CPAN if really needed.
    – Marki555
    Jan 13, 2016 at 8:20
  • 5
    @Ether With all due respect, I really appreciate knowing that this is a non-core module. This post is talking about using a module in lieu of a fairly simple regex one-liner. If the module is core, I would be much more open to it. It is relevant in this case.
    – UncleCarl
    Mar 1, 2018 at 16:57
31

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;
}
11

According to this perlmonk's thread:

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

Complete howto in the perfaq here: http://learn.perl.org/faq/perlfaq4.html#How-do-I-strip-blank-space-from-the-beginning-end-of-a-string-

4

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.

4

One option is Text::Trim:

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

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

3

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

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

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

2
  • That would remove spaces between words, not just at either end of the string.
    – DarenW
    May 1, 2012 at 18:06
  • @DarenW: depends how you use it. May 2, 2012 at 11:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.