I know that the following three lines of codes aim to extract the string into $value and store it in $header. But I do not know what are the differences between $value =~ s/^\s+//;
and $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.
And from 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
^ means starts with, $ means ends with this string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With