/patten/ is a default style of RE, it's actually m/patten/.
Only use / the 'm' can be missing, otherwise 'm' must be there.
Only use / the 'm' can be missing, otherwise 'm' must be there.
m{patten}
m|patten|
m(patten)
m[patten]
m#patten#
m*patten*
m%patten%
m|patten|
m(patten)
m[patten]
m#patten#
m*patten*
m%patten%
If we want use '^http://' as a patten, it's better not use '/'
m{^http://} is good, otherwise we must write /^http:\/\//
There're some symbol called 'flag' can control the matching of patten, such as /i /s /x
/i makes patten case insensitive.
print "Would you like to play a game? ";
chomp($_=<STDIN>);
if(/yes/i){
print "In that case, I recommend that you go bowling.\n";
}
chomp($_=<STDIN>);
if(/yes/i){
print "In that case, I recommend that you go bowling.\n";
}
/s makes '.' match any character including "\n".
$_="I saw Barney\ndown at the bowling alley\nwith fred\nlast night.\n";
if(/Barney.*fred/s){
print "That string mentions fred after Barney!\n";
}
if(/Barney.*fred/s){
print "That string mentions fred after Barney!\n";
}
/x makes space characters can be added into patten, just fit for human reading. The #comments can also added in patten with /x
/ -? \d+ /.? \d* /x
/
-? # 0 or 1 '-'
\d+ # 1 or more number
\.? # 0 or 1 '.'
\d* # 0 or more number
/x
-? # 0 or 1 '-'
\d+ # 1 or more number
\.? # 0 or 1 '.'
\d* # 0 or more number
/x
/i /s /x can be used together, the order makes no difference.
if(/barney.*fred/is){
print "That string mentions Fred after Barney!\n";
}
print "That string mentions Fred after Barney!\n";
}
^ matches the beginning of string, $ matches the end of string including "\n", /^fred$/ matches "fred" and "fred\n"
\b matches the edge of "words", "words" in Perl means \w+ that is [A-Za-z0-9_]+
Patten operates $_ be default, =~ makes it operate other strings.
my $some_other="I dream of betty rubble.";
if($some_other=~/\brub/){
print "Hey, there's the rub.\n";
}
if($some_other=~/\brub/){
print "Hey, there's the rub.\n";
}
转载于:https://blog.51cto.com/licong/1061958