perlfaq6.pod
来自「视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.」· POD 代码 · 共 1,005 行 · 第 1/3 页
POD
1,005 行
The use of C<\Q> causes the <.> in the regex to be treated as aregular character, so that C<P.> matches a C<P> followed by a dot.=head2 What is C</o> really for?X</o, regular expressions> X<compile, regular expressions>(contributed by brian d foy)The C</o> option for regular expressions (documented in L<perlop> andL<perlreref>) tells Perl to compile the regular expression only once.This is only useful when the pattern contains a variable. Perls 5.6and later handle this automatically if the pattern does not change.Since the match operator C<m//>, the substitution operator C<s///>,and the regular expression quoting operator C<qr//> are double-quotishconstructs, you can interpolate variables into the pattern. See theanswer to "How can I quote a variable to use in a regex?" for moredetails.This example takes a regular expression from the argument list andprints the lines of input that match it: my $pattern = shift @ARGV; while( <> ) { print if m/$pattern/; }Versions of Perl prior to 5.6 would recompile the regular expressionfor each iteration, even if C<$pattern> had not changed. The C</o>would prevent this by telling Perl to compile the pattern the firsttime, then reuse that for subsequent iterations: my $pattern = shift @ARGV; while( <> ) { print if m/$pattern/o; # useful for Perl < 5.6 }In versions 5.6 and later, Perl won't recompile the regular expressionif the variable hasn't changed, so you probably don't need the C</o>option. It doesn't hurt, but it doesn't help either. If you want anyversion of Perl to compile the regular expression only once even ifthe variable changes (thus, only using its initial value), you stillneed the C</o>.You can watch Perl's regular expression engine at work to verify foryourself if Perl is recompiling a regular expression. The C<use re'debug'> pragma (comes with Perl 5.005 and later) shows the details.With Perls before 5.6, you should see C<re> reporting that itscompiling the regular expression on each iteration. With Perl 5.6 orlater, you should only see C<re> report that for the first iteration. use re 'debug'; $regex = 'Perl'; foreach ( qw(Perl Java Ruby Python) ) { print STDERR "-" x 73, "\n"; print STDERR "Trying $_...\n"; print STDERR "\t$_ is good!\n" if m/$regex/; }=head2 How do I use a regular expression to strip C style comments from a file?While this actually can be done, it's much harder than you'd think.For example, this one-liner perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.cwill work in many but not all cases. You see, it's too simple-minded forcertain kinds of C programs, in particular, those with what appear to becomments in quoted strings. For that, you'd need something like this,created by Jeffrey Friedl and later modified by Fred Curtis. $/ = undef; $_ = <>; s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $2 ? $2 : ""#gse; print;This could, of course, be more legibly written with the C</x> modifier, addingwhitespace and comments. Here it is expanded, courtesy of Fred Curtis. s{ /\* ## Start of /* ... */ comment [^*]*\*+ ## Non-* followed by 1-or-more *'s ( [^/*][^*]*\*+ )* ## 0-or-more things which don't start with / ## but do end with '*' / ## End of /* ... */ comment | ## OR various things which aren't comments: ( " ## Start of " ... " string ( \\. ## Escaped char | ## OR [^"\\] ## Non "\ )* " ## End of " ... " string | ## OR ' ## Start of ' ... ' string ( \\. ## Escaped char | ## OR [^'\\] ## Non '\ )* ' ## End of ' ... ' string | ## OR . ## Anything other char [^/"'\\]* ## Chars which doesn't start a comment, string or escape ) }{defined $2 ? $2 : ""}gxse;A slight modification also removes C++ comments, as long as they are notspread over multiple lines using a continuation character): s#/\*[^*]*\*+([^/*][^*]*\*+)*/|//[^\n]*|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $2 ? $2 : ""#gse;=head2 Can I use Perl regular expressions to match balanced text?X<regex, matching balanced test> X<regexp, matching balanced test>X<regular expression, matching balanced test>Historically, Perl regular expressions were not capable of matchingbalanced text. As of more recent versions of perl including 5.6.1experimental features have been added that make it possible to do this.Look at the documentation for the (??{ }) construct in recent perlre manualpages to see an example of matching balanced parentheses. Be sure to takespecial notice of the warnings present in the manual before making useof this feature.CPAN contains many modules that can be useful for matching textdepending on the context. Damian Conway provides some usefulpatterns in Regexp::Common. The module Text::Balanced provides ageneral solution to this problem.One of the common applications of balanced text matching is workingwith XML and HTML. There are many modules available that supportthese needs. Two examples are HTML::Parser and XML::Parser. Thereare many others.An elaborate subroutine (for 7-bit ASCII only) to pull out balancedand possibly nested single chars, like C<`> and C<'>, C<{> and C<}>,or C<(> and C<)> can be found inhttp://www.cpan.org/authors/id/TOMC/scripts/pull_quotes.gz .The C::Scan module from CPAN also contains such subs for internal use,but they are undocumented.=head2 What does it mean that regexes are greedy? How can I get around it?X<greedy> X<greediness>Most people mean that greedy regexes match as much as they can.Technically speaking, it's actually the quantifiers (C<?>, C<*>, C<+>,C<{}>) that are greedy rather than the whole pattern; Perl prefers localgreed and immediate gratification to overall greed. To get non-greedyversions of the same quantifiers, use (C<??>, C<*?>, C<+?>, C<{}?>).An example: $s1 = $s2 = "I am very very cold"; $s1 =~ s/ve.*y //; # I am cold $s2 =~ s/ve.*?y //; # I am very coldNotice how the second substitution stopped matching as soon as itencountered "y ". The C<*?> quantifier effectively tells the regularexpression engine to find a match as quickly as possible and passcontrol on to whatever is next in line, like you would if you wereplaying hot potato.=head2 How do I process each word on each line?X<word>Use the split function: while (<>) { foreach $word ( split ) { # do something with $word here } }Note that this isn't really a word in the English sense; it's justchunks of consecutive non-whitespace characters.To work with only alphanumeric sequences (including underscores), youmight consider while (<>) { foreach $word (m/(\w+)/g) { # do something with $word here } }=head2 How can I print out a word-frequency or line-frequency summary?To do this, you have to parse out each word in the input stream. We'llpretend that by word you mean chunk of alphabetics, hyphens, orapostrophes, rather than the non-whitespace chunk idea of a word givenin the previous question: while (<>) { while ( /(\b[^\W_\d][\w'-]+\b)/g ) { # misses "`sheep'" $seen{$1}++; } } while ( ($word, $count) = each %seen ) { print "$count $word\n"; }If you wanted to do the same thing for lines, you wouldn't need aregular expression: while (<>) { $seen{$_}++; } while ( ($line, $count) = each %seen ) { print "$count $line"; }If you want these output in a sorted order, see L<perlfaq4>: "How do Isort a hash (optionally by value instead of key)?".=head2 How can I do approximate matching?X<match, approximate> X<matching, approximate>See the module String::Approx available from CPAN.=head2 How do I efficiently match many regular expressions at once?X<regex, efficiency> X<regexp, efficiency>X<regular expression, efficiency>( contributed by brian d foy )Avoid asking Perl to compile a regular expression every timeyou want to match it. In this example, perl must recompilethe regular expression for every iteration of the foreach()loop since it has no way to know what $pattern will be. @patterns = qw( foo bar baz ); LINE: while( <DATA> ) { foreach $pattern ( @patterns ) { if( /\b$pattern\b/i ) { print; next LINE; } } }The qr// operator showed up in perl 5.005. It compiles aregular expression, but doesn't apply it. When you use thepre-compiled version of the regex, perl does less work. Inthis example, I inserted a map() to turn each pattern intoits pre-compiled form. The rest of the script is the same,but faster. @patterns = map { qr/\b$_\b/i } qw( foo bar baz ); LINE: while( <> ) { foreach $pattern ( @patterns ) { print if /$pattern/i; next LINE; } }In some cases, you may be able to make several patterns intoa single regular expression. Beware of situations that requirebacktracking though. $regex = join '|', qw( foo bar baz ); LINE: while( <> ) { print if /\b(?:$regex)\b/i; }For more details on regular expression efficiency, see MasteringRegular Expressions by Jeffrey Freidl. He explains how regularexpressions engine work and why some patterns are surprisinglyinefficient. Once you understand how perl applies regularexpressions, you can tune them for individual situations.=head2 Why don't word-boundary searches with C<\b> work for me?X<\b>(contributed by brian d foy)Ensure that you know what \b really does: it's the boundary between aword character, \w, and something that isn't a word character. Thatthing that isn't a word character might be \W, but it can also be thestart or end of the string.It's not (not!) the boundary between whitespace and non-whitespace,and it's not the stuff between words we use to create sentences.In regex speak, a word boundary (\b) is a "zero width assertion",meaning that it doesn't represent a character in the string, but acondition at a certain position.For the regular expression, /\bPerl\b/, there has to be a wordboundary before the "P" and after the "l". As long as something otherthan a word character precedes the "P" and succeeds the "l", thepattern will match. These strings match /\bPerl\b/. "Perl" # no word char before P or after l "Perl " # same as previous (space is not a word char) "'Perl'" # the ' char is not a word char "Perl's" # no word char before P, non-word char after "l"These strings do not match /\bPerl\b/. "Perl_" # _ is a word char! "Perler" # no word char before P, but one after lYou don't have to use \b to match words though. You can look fornon-word characters surrounded by word characters. These stringsmatch the pattern /\b'\b/. "don't" # the ' char is surrounded by "n" and "t" "qep'a'" # the ' char is surrounded by "p" and "a"These strings do not match /\b'\b/.
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?