转自http://blog.csdn.net/blog_abel/article/details/40589227 侵删
一. 介绍
使用 s/regex/replacement/modifiers
进行查找替换
二. 实例
(1) s///
$f = "'quoted words'";
#进行模式匹配,下面方法去除''单引号
if($f =~ s/^'(.*)'$/$/) { #true, $1指的是引用了第一组(.*)的内容, ^$这两个字符用来表示开始与结束 print "matches","\n"; # mathces
print $f,"\n"; # quoted words
# 注意 标量$f 匹配后本身内容发生了变化
}
(2) s///r
用它进行匹配后,原始标量的值不会发生变化,可以把新值赋值给一个新的标量
$f = "'quoted words'";
#进行模式匹配,下面方法去除''单引号
$n = $f =~ s/^'(.*)'$/$/r; print "matches","\n";
print $f,"\n"; # quoted words # 注意 标量$f 匹配后本身内容无变化 print $n,"\n"; # 'quoted words' # 注意 $n
(3) s///g 多次查找替换
$z = "time hcat to feed the cat hcat";
$z =~ s/cat/AAA/g;#替换多次
print $z,"\n"; #结果为 time hAAA to feed the AAA hAAA
(4) s///e 求值
# reverse all the words in a string
$x = "the cat in the hat";
$x =~ s/(\w+)/reverse $/ge; # $x contains "eht tac ni eht tah" # convert percentage to decimal
$x = "A 39% hit rate";
$x =~ s!(\d+)%!$/!e; # $x contains "A 0.39 hit rate"
(5) s/// 可以用 s!!! , s{}{} , s{}// 进行替换