[ACCEPTED]-In Perl, what is the difference between s/^\s+// and s/\s+$//?-perl

Accepted answer
Score: 14

From perldoc perlfaq4:

How do I strip blank space from the beginning/end of a string?

A substitution can do this for you. For 22 a single line, you want to replace all 21 the leading or trailing whitespace with 20 nothing. You can do that with a pair of 19 substitutions:


You can also write that as 18 a single substitution, although it turns out 17 the combined statement is slower than the 16 separate ones. That might not matter to 15 you, though:


In this regular expression, the 14 alternation matches either at the beginning 13 or the end of the string since the anchors 12 have a lower precedence than the alternation. With 11 the /g flag, the substitution makes all 10 possible matches, so it gets both. Remember, the 9 trailing newline matches the \s+, and the 8 $ anchor can match to the absolute end 7 of the string, so the newline disappears 6 too.

And from perldoc perlrequick:

To specify where it should 5 match, we would use the anchor metacharacters 4 ^ and $ . The anchor ^ means match at the beginning 3 of the string and the anchor $ means match 2 at the end of the string, or before a 1 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
Score: 1

^ means starts with, $ means ends with this 1 string.

Score: 1

The first one will only replace whitespace 1 at the beginning of the line.

More Related questions