注意: 由于此blog不能显示反斜线,故用&&代替反斜线.
1. Matches with m//.
匹配操作(m/string/) 的简写形式 /string/, 也可以用m/string/的等价式m(string), m, m{string}, m[string],m,string,,m!string!,m^string^,等. 如果匹配,返回true,否则为false
2. Matches Option Modifiers
a. 大小写不敏感选项 /i
如果没有/i,是大小写敏感的.
print "Would you like to play a game? ";
chomp($_ = );
if (/yes/i) { # case-insensitive match
print "In that case, I recommend that you go bowling.n";
}
b. 匹配任何字符 /s
默认情况下.不匹配新行,而只能在一行内匹配,如果加了/s选项则可以匹配新行,就象[&&d&&D]一样能匹配任意字符。
$_ = "I saw Barneyndown at the bowling alleynwith Frednlast night.n";
if (/Barney.*Fred/s) {
print "That string mentions Fred after Barney!n";
}
note:Without the /s modifier, that match would fail since the two names aren't on the same line.
c. 允许模式中的空格选项 /x
默认的模式中如果有空格,表示匹配有空格的string,如果加上 /x 选项则忽略中间空格.(目的是使得模式清晰) 。
/-?d+.?d*/ # what is this doing?
/ -? d+ .? d* /x # a little better
/
-? # an optional minus sign
d+ # one or more digits before the decimal point
.? # an optional decimal point
d* # some optional digits after the decimal point
/x # end of pattern
#good style
d. 选项的复合.
if (/barney.*fred/is) { # both /i and /s
print "That string mentions Fred after Barney!n";
}
3. Anchors 锚.
行首标识符 ^
行尾标识符 $
“词”边界标识符 b, “词”可以由下划线,数字,字母组成。
/&&bfred&&b/将匹配单词fred, 不会匹配frederick, alfred.
/abc123&&b/可以匹配abc123- ,但abc123_却不可以。这就是因为下划线是“词”的边界,而横线不是词的边界。
4. The Binding Operator, =~ (绑定操作符)
默认匹配字符串变量是$_, 如 if (/ string /)....
如果要让指定的变量来匹配则需要绑定操作符 =~, 如下
my $some_other = "I dream of betty rubble.";
if ($some_other =~ /brub/) {
print "Aye, there's the rub.n";
}
又如
print "Do you like Perl? ";
my $likes_perl = ( =~ /byesb/i);
... # Time passes...
if ($likes_perl) {
print "You said earlier that you like Perl, so...n";
...
未完待续
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/88842/viewspace-979450/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/88842/viewspace-979450/