Is there a built-in function to trim leading and trailing whitespace such that trim(\" hello world \") eq \"hello world\"
?
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+$//;
According to this perlmonk's thread:
$string =~ s/^\s+|\s+$//g;
No, but you can use the s///
substitution operator and the \s
whitespace assertion to get the same result.
I also use a positive lookahead to trim repeating spaces inside the text:
s/^\s+|\s(?=\s)|\s+$//g