语法介绍:
$_ = "yabba dabba doo";
if (/abba/) {
print "It matched!\n";
}
if语句的条件表达式中,/ /是匹配操作符,默认用它匹配$_中的字符。
/ /匹配操作符中的空格有效
案例练习:
利用文件句柄读取和写入文件,并替换某一行中的特定内容,输出至另外一行:(喜大普奔,我做出来了。小菜菜,三瓜俩枣就开心的不得了)
原文件 pattern.perl:
while( <STDIN> ) {
chomp;
if ( /PATTERN_GOES_HERE/) {
print "\tMatches\n";
}
else {
print "\tDoesn't match\n";
}
}
将PATTERN_GOES_HERE修改为fred的脚本:
open(DATA1,"<./pattern.perl") or die "pattern.perl can not be opened!";
open(DATA2,">./pattern.fred.perl") or die "pattern.perl can not be opened!";
while(<DATA1>) {
if( /PATTERN_GOES_HERE/ ) {
$_ =~ s/PATTERN_GOES_HERE/fred/s;
print DATA2 "$_";
} else {
print DATA2 "$_";
}
}
close(DATA1) || die "file is cannot closed";
close(DATA2) || die "file is cannot closed";
修改后的结果 parttern.fred.perl:
while( <STDIN> ) {
chomp;
if ( /PATTERN_GOES_HERE/) {
print "\tMatches\n";
}
else {
print "\tDoesn't match\n";
}
}