一. 介紹
使用 s/regex/replacement/modifiers
進行查找替換
二. 執行個體
(1) s///
$f = "'quoted words'";
#進行模式比對,下面方法去除''單引号
if($f =~ s/^'(.*)'$/$1/) { #true, $1指的是引用了第一組(.*)的内容, ^$這兩個字元用來表示開始與結束
print "matches","\n"; # mathces
print $f,"\n"; # quoted words
# 注意 标量$f 比對後本身内容發生了變化
}
(2) s///r
用它進行比對後,原始标量的值不會發生變化,可以把新值指派給一個新的标量
$f = "'quoted words'";
#進行模式比對,下面方法去除''單引号
$n = $f =~ s/^'(.*)'$/$1/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 $1/ge; # $x contains "eht tac ni eht tah"
# convert percentage to decimal
$x = "A 39% hit rate";
$x =~ s!(\d+)%!$1/100!e; # $x contains "A 0.39 hit rate"
(5) s/// 可以用 s!!! , s{}{} , s{}// 進行替換