是否有一个内置的功能来修剪前导和尾随空格,使 trim(" hello world ") eq "hello world"?
trim(" hello world ") eq "hello world"
According to this perlmonk's thread:
$string =~ s/^\s+|\s+$//g;
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
There's no built-in trim function, but you can easily implement your own using a simple substitution:
trim
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; }
Apply: s/^\s*//; s/\s+$//; to it. Or use s/^\s+|\s+$//g if you want to be fancy.
s/^\s*//; s/\s+$//;
s/^\s+|\s+$//g
No, but you can use the s/// substitution operator and the \s whitespace assertion to get the same result.
s///
\s
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-
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.
String::Util
[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+$//;
I also use a positive lookahead to trim repeating spaces inside the text:
s/^\s+|\s(?=\s)|\s+$//g
One option is Text::Trim:
use Text::Trim; print trim(" example ");
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.