Perl Learning - 15 (s)

Perl Learning - 15 (s),第1张

概述s/// is the most common expression using RE to do "search and replace".   s/patten/replace/ searches the 'patten' and replaces it to 'replace'.   'patten' is the patten we talked in perlRE, it can be s/// is the most common Expression using RE to do "search and replace".   s/patten/replace/ searches the 'patten' and replaces it to 'replace'.   'patten' is the patten we talked in perlRE,it can be a variable though.
'replace' is the characters whichever you want to replace the result of search,it can be variable too.   $_="He's out bowling with barney tonight.";
s/barney/Fred/; # barney replaced by Fred
s/with (\w+)/agaist $1's team/;
print "$_\n";   s/// returns a value: replace success returns true,failure returns false.   $_="fred flintstone";
if(s/fred/wilma/){
 print "Successfully replaced fred with wilma!\n";
 print "$_\n";
}   /g flag can replace all the result,instead of once by default.   $_="home,sweet home!";
s/home/cave/g;
print "$_\n";   $_="   input     data may have      extra whitespace.  ";
s/\s+/ /g;
print "$_\n";   Above example is used to compress multiple whitespaces to one single space.   We can use other symbol in other then s///   $_="   input     data may have      extra whitespace.  ";
s<\s+>[ ]g;
s(^\s+)<>g;
s#\s+$##g;
print "$_\n";   Note if use the patten symbols different from replace symbols,they need two pairs of () [] {} ... those pair'ed symbols. /// ### !!! ... those single don't have to.   Flags /i /x /s used in m// can also be used in s///   $_="hello 1
hello 2
wilma again
Lol
Fred,WILMA come on!
_ _END_ _
line 1
line 2
line 3";
 s#wilma#Wilma#gi;
 s{_ _END_ _.*}{}gs;
 print;   All wilma/wiLMA/WIlmA are replaced by Wilma,lines starting with '_ _END_ _' all are deleted.   Also,=~ can be used to replace variables other than $_ by default.   $file_name =~ s#^.*/##s; # remove all unix style path   /U changes all characters after it to upper case;
/L changes all characters after it to lower case;
/E close the window of /U or /L;
/u changes one character after it to upper case;
/l changes one character after it to loser case;
/u/L changes one character after it to upper case and all other characters to lower case;
/l/U changes one character after it to lower case and all other characters to upper case.   $_ =“I saw barney with Fred.”;
s/(fred|barney)/\U$1/gi;   $_="I saw barney with FREd.";
s/(\w+) with (\w+)/\u\L$2\E with \u\L$1/i;
print "$_\n";   They can be used in " " as well:   $name="fred flintstone";print "Hello,\L\u$name\E,would you liKE to play a game?\n"; 总结

以上是内存溢出为你收集整理的Perl Learning - 15 (s///)全部内容,希望文章能够帮你解决Perl Learning - 15 (s///)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1293051.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-10
下一篇 2022-06-10

发表评论

登录后才能评论

评论列表(0条)

保存