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

I know that the next three lines of code tend to extract the string into the value of $ and store it in the $ header. But I do not know what the differences are between $value =~ s/^\s+//; and $value =~ s/\s+$//; .

 $value =~ s/^\s+//; $value =~ s/\s+$//; $header[$i]= $value; 
+8
regex perl
source share
3 answers

From perldoc perlfaq4 :

How to remove empty space from the beginning / end of a line?

Substitution can do this for you. For one line, you want to replace all leading or trailing spaces with nothing. You can do this with a couple of permutations:

 s/^\s+//; s/\s+$//; 

You can also write this as a single substitution, although it becomes from a combined statement to be slower than separate ones. What might not matter to you:

 s/^\s+|\s+$//g; 

In this regex, alternation matches either the beginning or the end of the line, since anchors are lower than alternation. With the /g flag, the replacement makes all possible matches, so it gets both. Remember that newline matches \s+ , and the $ binding can match the absolute end of the line, so the new line also disappears.


And from perldoc perlrequick :

To indicate where it should match, we would use the anchor metacharacters ^ and $ . An anchor ^ means matching at the beginning of a line and binding $ means matching at the end of a line or before a new line at the end of a line. Some examples:

 "housekeeper" =~ /keeper/; # matches "housekeeper" =~ /^keeper/; # doesn't match "housekeeper" =~ /keeper$/; # matches "housekeeper\n" =~ /keeper$/; # matches "housekeeper" =~ /^housekeeper$/; # matches 
+10
source share

^ means that starts with $, ends with this line.

+1
source share

The first will replace the spaces at the beginning of the line.

+1
source share

All Articles