s/// will make just one replacement, even if others are possible. The /g modifier tells
s/// to make all possible nonoverlapping* replacements:
- $_ = "home, sweet home!";
-
s/home/cave/g;
-
print "$_\n"; # "cave, sweet cave!"
Once we show collapsing whitespace, everyone wants to know about stripping leading
and trailing whitespace. That’s easy enough, in two steps:
s/^\s+//; # Replace leading whitespace with nothing
s/\s+$//; # Replace trailing whitespace with nothing
We could do that in one step with an alternation and the /g flag, but that turns out to
be a bit slower, at least when we wrote this. The regular expression engine is always
being tuned, but to learn more about that, you can get Jeffrey Friedl’s Mastering Regular
Expressions (O’Reilly) and find out what makes regular expressions fast (or slow).
s/^\s+|\s+$//g; # Strip leading, trailing whitespace.
The \U escape forces what follows to all uppercase:
$_ = "I saw Barney with Fred.";
s/(fred|barney)/\U$1/gi; # $_ is now "I saw BARNEY with FRED."
Similarly, the \L escape forces lowercase. Continuing from the previous code:
s/(fred|barney)/\L$1/gi; # $_ is now "I saw barney with fred."
By default, these affect the rest of the (replacement) string, or you can turn off case
shifting with \E:
s/(\w+) with (\w+)/\U$2\E with $1/i; # $_ is now "I saw FRED with barney."
When written in lowercase (\l and \u ), they affect only the next character:
s/(fred|barney)/\u$1/ig; # $_ is now "I saw FRED with Barney."
You can even stack them up. Using \u with \L means “all lowercase, but capitalize the
first letter”:*
s/(fred|barney)/\u\L$1/ig; # $_ is now "I saw Fred with Barney."
As it happens, although we’re covering case shifting in relation to substitutions, these
escape sequences are available in any double-quotish string:
print "Hello, \L\u$name\E, would you like to play a game?\n";
阅读(454) | 评论(0) | 转发(0) |