注意: 符号&&表示反斜线
1. s/pattern/new string/ 文本替换.
把$_用模式pattern匹配,匹配到的用new string替换.成功替换返回true, 否则false
例.1
$_ = "green scaly dinosaur";
s/(&&w+) (&&w+)/$2, $1/; # Now it's "scaly, green dinosaur"
s/^/huge, /; # Now it's "huge, scaly, green dinosaur"
s/,.*een//; # Empty replacement: Now it's "huge dinosaur"
s/green/red/; # Failed match: still "huge dinosaur"
s/&&w+$/($`!)$&/; # Now it's "huge (huge !)dinosaur"
s/&&s+(!&&W+)/$1 /; # Now it's "huge (huge!) dinosaur"
s/huge/gigantic/; # Now it's "gigantic (huge!) dinosaur"
例2.
$_ = "fred flintstone";
if (s/fred/wilma/) {
print "Successfully replaced fred with wilma!";
}
a. 全局替换选项 /g
例3.
$_ = "home, sweet home!";
s/home/cave/g;
print "$_"; # "cave, sweet cave!"
例4.把一个以上的空格替换为一个空格
$_ = "Input data&&t may have extra whitespace.";
s/&&s+/ /g; # Now it says "Input data may have extra whitespace."
例5.去掉行头,行尾的空格
s/^&&s+|&&s+$//g; # Strip leading, trailing whitespace
b. s///的不同分割符.
s#pattern#new string#
s{pattern}{new string}
s[pattern](new string)
s#new string#
c.匹配大小写选项 /i
例6.
s#wilma#Wilma#gi; # replace every WiLmA or WILMA with Wilma
d. 替换绑定操作符
$var =~ s#pattern#new string#;
例7.
$file_name =~ s#^.*/##s; # In $file_name, remove any Unix-style path
e. 大小写转换选项.
转换匹配到的变量为大写 &&U
$_ = "I saw Barney with Fred.";
s/(fred|barney)/&&U$_ is now "I saw BARNEY with FRED."
转换匹配到的变量为小写 &&L
s/(fred|barney)/&&L$1/gi; # $_ is now "I saw barney with fred."
默认情况下,当用&&L或&&U影响后面的替代,&&E则可以关闭这种影响。
s/(&&w+) with (&&w+)/&&U$2&&E with $1/i; # $_ is now "I saw FRED with barney."
只转换匹配字符串的首字符选项&&l转换到小写, &&u转换到大写
s/(fred|barney)/&&u$1/ig; # $_ is now "I saw FRED with Barney."
也可以把它们中的几个放一起,所有都转换为小写,除了大写首字符
s/(fred|barney)/&&u&&L$1/ig; # $_ is now "I saw Fred with Barney."
这些选项也可用在双引号中,
print "Hello, &&L&&u$name&&E, would you like to play a game?&&n";
2. 分割操作 split/delimiter/, string
把string用delimiter分割成多个子字符串组成的数组(返回值).
@fields = split /:/, "abc:def:g:h"; # gives ("abc", "def", "g", "h")
有可能返回包含空的字符串
@fields = split /:/, "abc:def::g:h"; # gives ("abc", "def", "", "g", "h")
还有个规则,在分割开始处可以包含空字符串,但是尾部的空字符串则丢弃
@fields = split /:/, ":::a:b:c:::"; # gives ("", "", "", "a", "b", "c")
分割符也可以用模式
my $some_input = "This is a &&t test.&&n";
my @args = split /&&s+/, $some_input; # ("This", "is", "a", "test.")
默认用空格分割$_
my @fields = split; # like split /&&s+/, $_;
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/88842/viewspace-980220/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/88842/viewspace-980220/