perl学习笔记-4
#Example17 #用 s/// 替换
#!/usr/bin/perl
$_ = "He's out bowling with Barney tonight.";
$s=s/Barney/Fred/;
print "$_\n"; #输出替换后的字符串
print "$s\n"; #输出替换命令执行的结果:1 ,若替换失败,返回空值
$_ = "green scaly dinosaur";
print "$_\n"; #green scaly dinosaur
s/(\w+) (\w+)/$2, $1/; #将第一个,第二个单词调换一下位置
print "$_\n"; #scaly, green dinosaur
s/^/huge, /; #行首加上'huge, '
print "$_\n"; #huge, scaly, green dinosaur
s/,.*een//; #匹配第一个','到'een'之间所有字符,并删掉
print "$_\n"; #huge dinosaur
s/green/red/; #green已经没有了,上面也不做
print "$_\n"; #huge dinosaur
s/\w+$/($`!)$&/; #先找到最后一个单词,然后在他($&)前面插入该词之前的部分($`)和一个'!'
#也就是替换为 该词之前的部分($`)和一个'!'该词 <=> ($`!)$&
print "$_\n"; #huge (huge !)dinosaur
s/\s+(!\W+)/$1 /; #匹配 一个空格、叹号、非字符,然后替换成 叹号、非字符、空格
print "$_\n"; #huge (huge!) dinosaur
s/huge/gigantic/; #替换单词huge(前后不能有字符)
print "$_\n"; #gigantic (huge!) dinosaur
#Example18 # s/// 的定界符'/'的不同写法
#!/usr/bin/perl
$_ = "He's out bowling with Barney tonight.";
s/Barney/Fred/; #规范写法
print "$_\n";
s#Fred#Barney#; #可以用'#'替换'/'
print "$_\n";
s{Barney}{Fred}; #也可以不使用定界符,而是用成对出现的符号
print "$_\n";
s(Fred){Barney}; #成对出现的符号只需要成对出现,两对之间没有关联
print "$_\n";
#Example19 #可选修饰符 /g 全局匹配 /i 忽略大小写 /s 任意字符 /x 加入空白
#!/usr/bin/perl #单词锚位 /b 单词边界锚位 ^(脱字符) 行首 $(美元符号) 行尾
$_ = "He's out bowling with Barney tonight.";
print "$_\n";
s#o#n#g; #全局匹配,将所有的'o'换成'n'
print "$_\n";
s#he#We#gi; #全局匹配,将所有的'he'换成'We',并且忽略大小写(只忽略he的大小写)
print "$_\n";
s#(bnwling|Barney)#\L$1#gi; #忽略大小写全局匹配,将Barney或bnwling转换称小写
print "$_\n";
s#(Barney|bnwling)#\U$1#gi; #忽略大小写全局匹配,将Barney或bnwling转换称大写
print "$_\n";
s#(bnwling|Barney|we)#\l$1#gi; #忽略大小写全局匹配,将Barney或bnwling或we的首字母转换称大写
print "$_\n";
s#(we)#\u$1#gi; #忽略大小写全局匹配,将we的首字母转换称大写
print "$_\n";
#Example19 #split函数:以指定分隔符切割字符串
#!/usr/bin/perl
$_ = "He's out bowling with Barney tonight.";
print "$_\n";
@ff = split ; #以默认分隔符(空格)切割字符串$_,并将结果保存到@ff中
print "@ff\n";
print @ff;
@ff = split /:/, "He's :abc :xxd"; #得到("He's ","abc ","xxd")
print "@ff\n"; #以':'为分隔符切割字符串"He's :abc :xxd",并将结果保存到@ff中
print @ff;
@ff = split /\s+/, " He's :abc :xxd"; #得到("He's",":abc",":xxd")
print "@ff\n"; #以空白符为分隔符切割字符串" He's :abc :xxd",并将结果保存到@ff中
print @ff; #所有的空白(空格、制表符等)都被当做一个空格来处理,会自动舍弃前面的空白
@ff = split /:/, ":::He's::xxd:abc:dd::"; #得到的是(“ ”,“ ”,“He's”,“ ”,“xxd”,“abc”,“dd”)
print "@ff\n"; #保留前面和中间的空字符(串),自动舍弃后面的空字符(串)
print @ff;
@ff = split /:/, ":::He's::xxd:abc:dd::";
print "@ff\n"; #得到" He's xxd abc dd"
@ff = split /\s+/, "@ff"; #若想要处理字符串,需要加上引号
print "@ff\n"; #得到" He's xxd abc dd"
@ff = split /:/, ":::He's::xxd:abc:dd::";
print "@ff\n"; #得到" He's xxd abc dd"
@ff = split /\s+/, @ff; #若想要处理字符串,需要加上引号,否则处理的字符长度
print "@ff\n"; #得到8
#Example20 #join:用指定的分隔符将若干个字符(串)连接成一个字符串
#!/usr/bin/perl #和split刚好相反
my $x = join ":", 1, 2, 4, 6, 8; #得到"1:2:4:6:8"
print "$x\n";
print $x;
my @a = split /:/, $x; #得到"1 2 4 6 8"
print "@a\n";
my $x = join "-", @a; #得到"1-2-4-6-8"
print "$x\n";
while(<>){ #接收键盘的任意输入
chomp; #过滤最后的回车
print join("\t",(split /:/)), "\n"; #先以':'为分隔符分隔输入,再用'\t'连接字符
}