Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, what is the difference between s/^\s+// and s/\s+$//?

Tags:

regex

perl

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;
like image 419
user785099 Avatar asked Feb 13 '12 14:02

user785099


2 Answers

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
like image 67
Zaid Avatar answered Sep 30 '22 04:09

Zaid


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

like image 34
Mike Thomsen Avatar answered Sep 30 '22 04:09

Mike Thomsen