$value =~ s/^\s+//;
和 $value =~ s/\s+$//;
之间的区别。$value =~ s/^\s+//;
$value =~ s/\s+$//;
$header[$i]= $value;
$value =~ s/^\s+//;
和 $value =~ s/\s+$//;
之间的区别。$value =~ s/^\s+//;
$value =~ s/\s+$//;
$header[$i]= $value;
From perldoc perlfaq4
:
How do I strip blank space from the beginning/end of a string?
A substitution can do this for you. For a single line, you want to replace all the leading or trailing whitespace with nothing. You can do that with a pair of substitutions:
s/^\s+//; s/\s+$//;
You can also write that as a single substitution, although it turns out the combined statement is slower than the separate ones. That might not matter to you, though:
s/^\s+|\s+$//g;
In this regular expression, the alternation matches either at the beginning or the end of the string since the anchors have a lower precedence than the alternation. With the
/g
flag, the substitution makes all possible matches, so it gets both. Remember, the trailing newline matches the\s+
, and the$
anchor can match to the absolute end of the string, so the newline disappears too.
以下内容来源于perldoc perlrequick
:
To specify where it should match, we would use the anchor metacharacters
^
and$
. The anchor^
means match at the beginning of the string and the anchor$
means match at the end of the string, or before a newline at the end of the string. Some examples:"housekeeper" =~ /keeper/; # matches "housekeeper" =~ /^keeper/; # doesn't match "housekeeper" =~ /keeper$/; # matches "housekeeper\n" =~ /keeper$/; # matches "housekeeper" =~ /^housekeeper$/; # matches
^ 表示以此字符串开始,$ 表示以此字符串结束。
\z
,而不是$
。$
匹配字符串的结尾或者在字符串结尾前的换行符。 - ikegami第一个只会替换行首的空格。