perlop.1

来自「视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.」· 1 代码 · 共 1,599 行 · 第 1/5 页

1
1,599
字号
Since Perl may compile the pattern at the moment of execution of \fIqr()\fRoperator, using \fIqr()\fR may have speed advantages in some situations,notably if the result of \fIqr()\fR is used standalone:.Sp.Vb 11\&    sub match {\&        my $patterns = shift;\&        my @compiled = map qr/$_/i, @$patterns;\&        grep {\&            my $success = 0;\&            foreach my $pat (@compiled) {\&                $success = 1, last if /$pat/;\&            }\&            $success;\&        } @_;\&    }.Ve.SpPrecompilation of the pattern into an internal representation atthe moment of \fIqr()\fR avoids a need to recompile the pattern everytime a match \f(CW\*(C`/$pat/\*(C'\fR is attempted.  (Perl has many other internaloptimizations, but none would be triggered in the above example ifwe did not use \fIqr()\fR operator.).SpOptions are:.Sp.Vb 7\&    m   Treat string as multiple lines.\&    s   Treat string as single line. (Make . match a newline)\&    i   Do case\-insensitive pattern matching.\&    x   Use extended regular expressions.\&    p   When matching preserve a copy of the matched string so\&        that ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} will be defined.\&    o   Compile pattern only once..Ve.SpIf a precompiled pattern is embedded in a larger pattern then the effectof 'msixp' will be propagated appropriately.  The effect of the 'o'modifier has is not propagated, being restricted to those patternsexplicitly using it..SpSee perlre for additional information on valid syntax for \s-1STRING\s0, andfor a detailed look at the semantics of regular expressions..IP "m/PATTERN/msixpogc" 8.IX Xref "m operator, match regexp, options regexp regex, options regex  m  s  i  x  p  o  g  c".IX Item "m/PATTERN/msixpogc".PD 0.IP "/PATTERN/msixpogc" 8.IX Item "/PATTERN/msixpogc".PDSearches a string for a pattern match, and in scalar context returnstrue if it succeeds, false if it fails.  If no string is specifiedvia the \f(CW\*(C`=~\*(C'\fR or \f(CW\*(C`!~\*(C'\fR operator, the \f(CW$_\fR string is searched.  (Thestring specified with \f(CW\*(C`=~\*(C'\fR need not be an lvalue\*(--it may be theresult of an expression evaluation, but remember the \f(CW\*(C`=~\*(C'\fR bindsrather tightly.)  See also perlre.  See perllocale fordiscussion of additional considerations that apply when \f(CW\*(C`use locale\*(C'\fRis in effect..SpOptions are as described in \f(CW\*(C`qr//\*(C'\fR; in addition, the following matchprocess modifiers are available:.Sp.Vb 2\&    g   Match globally, i.e., find all occurrences.\&    c   Do not reset search position on a failed match when /g is in effect..Ve.SpIf \*(L"/\*(R" is the delimiter then the initial \f(CW\*(C`m\*(C'\fR is optional.  With the \f(CW\*(C`m\*(C'\fRyou can use any pair of non-alphanumeric, non-whitespace charactersas delimiters.  This is particularly useful for matching path namesthat contain \*(L"/\*(R", to avoid \s-1LTS\s0 (leaning toothpick syndrome).  If \*(L"?\*(R" isthe delimiter, then the match-only-once rule of \f(CW\*(C`?PATTERN?\*(C'\fR applies.If \*(L"'\*(R" is the delimiter, no interpolation is performed on the \s-1PATTERN\s0..Sp\&\s-1PATTERN\s0 may contain variables, which will be interpolated (and thepattern recompiled) every time the pattern search is evaluated, exceptfor when the delimiter is a single quote.  (Note that \f(CW$(\fR, \f(CW$)\fR, and\&\f(CW$|\fR are not interpolated because they look like end-of-string tests.)If you want such a pattern to be compiled only once, add a \f(CW\*(C`/o\*(C'\fR afterthe trailing delimiter.  This avoids expensive run-time recompilations,and is useful when the value you are interpolating won't change overthe life of the script.  However, mentioning \f(CW\*(C`/o\*(C'\fR constitutes a promisethat you won't change the variables in the pattern.  If you change them,Perl won't even notice.  See also \*(L"STRING/msixpo\*(R"\*(L" in \*(R"qr..SpIf the \s-1PATTERN\s0 evaluates to the empty string, the last\&\fIsuccessfully\fR matched regular expression is used instead. In thiscase, only the \f(CW\*(C`g\*(C'\fR and \f(CW\*(C`c\*(C'\fR flags on the empty pattern is honoured \-the other flags are taken from the original pattern. If no match haspreviously succeeded, this will (silently) act instead as a genuineempty pattern (which will always match)..SpNote that it's possible to confuse Perl into thinking \f(CW\*(C`//\*(C'\fR (the emptyregex) is really \f(CW\*(C`//\*(C'\fR (the defined-or operator).  Perl is usually prettygood about this, but some pathological cases might trigger this, such as\&\f(CW\*(C`$a///\*(C'\fR (is that \f(CW\*(C`($a) / (//)\*(C'\fR or \f(CW\*(C`$a // /\*(C'\fR?) and \f(CW\*(C`print $fh //\*(C'\fR(\f(CW\*(C`print $fh(//\*(C'\fR or \f(CW\*(C`print($fh //\*(C'\fR?).  In all of these examples, Perlwill assume you meant defined-or.  If you meant the empty regex, justuse parentheses or spaces to disambiguate, or even prefix the emptyregex with an \f(CW\*(C`m\*(C'\fR (so \f(CW\*(C`//\*(C'\fR becomes \f(CW\*(C`m//\*(C'\fR)..SpIf the \f(CW\*(C`/g\*(C'\fR option is not used, \f(CW\*(C`m//\*(C'\fR in list context returns alist consisting of the subexpressions matched by the parentheses in thepattern, i.e., (\f(CW$1\fR, \f(CW$2\fR, \f(CW$3\fR...).  (Note that here \f(CW$1\fR etc. arealso set, and that this differs from Perl 4's behavior.)  When there areno parentheses in the pattern, the return value is the list \f(CW\*(C`(1)\*(C'\fR forsuccess.  With or without parentheses, an empty list is returned uponfailure..SpExamples:.Sp.Vb 2\&    open(TTY, \*(Aq/dev/tty\*(Aq);\&    <TTY> =~ /^y/i && foo();    # do foo if desired\&\&    if (/Version: *([0\-9.]*)/) { $version = $1; }\&\&    next if m#^/usr/spool/uucp#;\&\&    # poor man\*(Aqs grep\&    $arg = shift;\&    while (<>) {\&        print if /$arg/o;       # compile only once\&    }\&\&    if (($F1, $F2, $Etc) = ($foo =~ /^(\eS+)\es+(\eS+)\es*(.*)/)).Ve.SpThis last example splits \f(CW$foo\fR into the first two words and theremainder of the line, and assigns those three fields to \f(CW$F1\fR, \f(CW$F2\fR, and\&\f(CW$Etc\fR.  The conditional is true if any variables were assigned, i.e., ifthe pattern matched..SpThe \f(CW\*(C`/g\*(C'\fR modifier specifies global pattern matching\*(--that is,matching as many times as possible within the string.  How it behavesdepends on the context.  In list context, it returns a list of thesubstrings matched by any capturing parentheses in the regularexpression.  If there are no parentheses, it returns a list of allthe matched strings, as if there were parentheses around the wholepattern..SpIn scalar context, each execution of \f(CW\*(C`m//g\*(C'\fR finds the next match,returning true if it matches, and false if there is no further match.The position after the last match can be read or set using the \fIpos()\fRfunction; see \*(L"pos\*(R" in perlfunc.   A failed match normally resets thesearch position to the beginning of the string, but you can avoid thatby adding the \f(CW\*(C`/c\*(C'\fR modifier (e.g. \f(CW\*(C`m//gc\*(C'\fR).  Modifying the targetstring also resets the search position..SpYou can intermix \f(CW\*(C`m//g\*(C'\fR matches with \f(CW\*(C`m/\eG.../g\*(C'\fR, where \f(CW\*(C`\eG\*(C'\fR is azero-width assertion that matches the exact position where the previous\&\f(CW\*(C`m//g\*(C'\fR, if any, left off.  Without the \f(CW\*(C`/g\*(C'\fR modifier, the \f(CW\*(C`\eG\*(C'\fR assertionstill anchors at \fIpos()\fR, but the match is of course only attempted once.Using \f(CW\*(C`\eG\*(C'\fR without \f(CW\*(C`/g\*(C'\fR on a target string that has not previously had a\&\f(CW\*(C`/g\*(C'\fR match applied to it is the same as using the \f(CW\*(C`\eA\*(C'\fR assertion to matchthe beginning of the string.  Note also that, currently, \f(CW\*(C`\eG\*(C'\fR is onlyproperly supported when anchored at the very beginning of the pattern..SpExamples:.Sp.Vb 2\&    # list context\&    ($one,$five,$fifteen) = (\`uptime\` =~ /(\ed+\e.\ed+)/g);\&\&    # scalar context\&    $/ = "";\&    while (defined($paragraph = <>)) {\&        while ($paragraph =~ /[a\-z][\*(Aq")]*[.!?]+[\*(Aq")]*\es/g) {\&            $sentences++;\&        }\&    }\&    print "$sentences\en";\&\&    # using m//gc with \eG\&    $_ = "ppooqppqq";\&    while ($i++ < 2) {\&        print "1: \*(Aq";\&        print $1 while /(o)/gc; print "\*(Aq, pos=", pos, "\en";\&        print "2: \*(Aq";\&        print $1 if /\eG(q)/gc;  print "\*(Aq, pos=", pos, "\en";\&        print "3: \*(Aq";\&        print $1 while /(p)/gc; print "\*(Aq, pos=", pos, "\en";\&    }\&    print "Final: \*(Aq$1\*(Aq, pos=",pos,"\en" if /\eG(.)/;.Ve.SpThe last example should print:.Sp.Vb 7\&    1: \*(Aqoo\*(Aq, pos=4\&    2: \*(Aqq\*(Aq, pos=5\&    3: \*(Aqpp\*(Aq, pos=7\&    1: \*(Aq\*(Aq, pos=7\&    2: \*(Aqq\*(Aq, pos=8\&    3: \*(Aq\*(Aq, pos=8\&    Final: \*(Aqq\*(Aq, pos=8.Ve.SpNotice that the final match matched \f(CW\*(C`q\*(C'\fR instead of \f(CW\*(C`p\*(C'\fR, which a matchwithout the \f(CW\*(C`\eG\*(C'\fR anchor would have done. Also note that the final matchdid not update \f(CW\*(C`pos\*(C'\fR \*(-- \f(CW\*(C`pos\*(C'\fR is only updated on a \f(CW\*(C`/g\*(C'\fR match. If thefinal match did indeed match \f(CW\*(C`p\*(C'\fR, it's a good bet that you're running anolder (pre\-5.6.0) Perl..SpA useful idiom for \f(CW\*(C`lex\*(C'\fR\-like scanners is \f(CW\*(C`/\eG.../gc\*(C'\fR.  You cancombine several regexps like this to process a string part-by-part,doing different actions depending on which regexp matched.  Eachregexp tries to match where the previous one leaves off..Sp.Vb 10\& $_ = <<\*(AqEOL\*(Aq;\&      $url = URI::URL\->new( "http://www/" );   die if $url eq "xXx";\& EOL\& LOOP:\&    {\&      print(" digits"),         redo LOOP if /\eG\ed+\eb[,.;]?\es*/gc;\&      print(" lowercase"),      redo LOOP if /\eG[a\-z]+\eb[,.;]?\es*/gc;\&      print(" UPPERCASE"),      redo LOOP if /\eG[A\-Z]+\eb[,.;]?\es*/gc;\&      print(" Capitalized"),    redo LOOP if /\eG[A\-Z][a\-z]+\eb[,.;]?\es*/gc;\&      print(" MiXeD"),          redo LOOP if /\eG[A\-Za\-z]+\eb[,.;]?\es*/gc;\&      print(" alphanumeric"),   redo LOOP if /\eG[A\-Za\-z0\-9]+\eb[,.;]?\es*/gc;\&      print(" line\-noise"),     redo LOOP if /\eG[^A\-Za\-z0\-9]+/gc;\&      print ". That\*(Aqs all!\en";\&    }.Ve.SpHere is the output (split into several lines):.Sp.Vb 4\& line\-noise lowercase line\-noise lowercase UPPERCASE line\-noise\& UPPERCASE line\-noise lowercase line\-noise lowercase line\-noise\& lowercase lowercase line\-noise lowercase lowercase line\-noise\& MiXeD line\-noise. That\*(Aqs all!.Ve.IP "?PATTERN?" 8.IX Xref "?".IX Item "?PATTERN?"This is just like the \f(CW\*(C`/pattern/\*(C'\fR search, except that it matches onlyonce between calls to the \fIreset()\fR operator.  This is a usefuloptimization when you want to see only the first occurrence ofsomething in each file of a set of files, for instance.  Only \f(CW\*(C`??\*(C'\fRpatterns local to the current package are reset..Sp.Vb 7\&    while (<>) {\&        if (?^$?) {\&                            # blank line between header and body\&        }\&    } continue {\&        reset if eof;       # clear ?? status for next file\&    }.Ve.SpThis usage is vaguely deprecated, which means it just might possiblybe removed in some distant future version of Perl, perhaps somewherearound the year 2168..IP "s/PATTERN/REPLACEMENT/msixpogce" 8.IX Xref "substitute substitution replace regexp, replace regexp, substitute  m  s  i  x  p  o  g  c  e".IX Item "s/PATTERN/REPLACEMENT/msixpogce"Searches a string for a pattern, and if found, replaces that patternwith the replacement text and returns the number of substitutionsmade.  Otherwise it returns false (specifically, the empty string)..SpIf no string is specified via the \f(CW\*(C`=~\*(C'\fR or \f(CW\*(C`!~\*(C'\fR operator, the \f(CW$_\fRvariable is searched and modified.  (The string specified with \f(CW\*(C`=~\*(C'\fR mustbe scalar variable, an array element, a hash element, or an assignmentto one of those, i.e., an lvalue.).SpIf the delimiter chosen is a single quote, no interpolation isdone on either the \s-1PATTERN\s0 or the \s-1REPLACEMENT\s0.  Otherwise, if the\&\s-1PATTERN\s0 contains a $ that looks like a variable rather than anend-of-string test, the variable will be interpolated into the patternat run-time.  If you want the pattern compiled only once the first timethe variable is interpolated, use the \f(CW\*(C`/o\*(C'\fR option.  If the patternevaluates to the empty string, the last successfully executed regularexpression is used instead.  See perlre for further explanation on these.See perllocale for discussion of additional considerations that applywhen \f(CW\*(C`use locale\*(C'\fR is in effect..SpOptions are as with m// with the addition of the following replacementspecific options:.Sp.Vb 2\&    e   Evaluate the right side as an expression.\&    ee  Evaluate the right side as a string then eval the result.Ve.SpAny non-alphanumeric, non-whitespace delimiter may replace theslashes.  If single quotes are used, no interpretation is done on thereplacement string (the \f(CW\*(C`/e\*(C'\fR modifier overrides this, however).  UnlikePerl 4, Perl 5 treats backticks as normal delimiters; the replacementtext is not evaluated as a command.  If the\&\s-1PATTERN\s0 is delimited by bracketing quotes, the \s-1REPLACEMENT\s0 has its ownpair of quotes, which may or may not be bracketing quotes, e.g.,\&\f(CW\*(C`s(foo)(bar)\*(C'\fR or \f(CW\*(C`s<foo>/bar/\*(C'\fR.  A \f(CW\*(C`/e\*(C'\fR will cause thereplacement portion to be treated as a full-fledged Perl expressionand evaluated right then and there.  It is, however, syntax checked atcompile-time. A second \f(CW\*(C`e\*(C'\fR modifier will cause the replacement portionto be \f(CW\*(C`eval\*(C'\fRed before being run as a Perl expression..SpExamples:.Sp.Vb 1\&    s/\ebgreen\eb/mauve/g;                # don\*(Aqt change wintergreen\&\&    $path =~ s|/usr/bin|/usr/local/bin|;\&\&    s/Login: $foo/Login: $bar/; # run\-time pattern\&\&    ($foo = $bar) =~ s/this/that/;      # copy first, then change\&\&    $count = ($paragraph =~ s/Mister\eb/Mr./g);  # get change\-count\&\&    $_ = \*(Aqabc123xyz\*(Aq;\&    s/\ed+/$&*2/e;               # yields \*(Aqabc246xyz\*(Aq\&    s/\ed+/sprintf("%5d",$&)/e;  # yields \*(Aqabc  246xyz\*(Aq\&    s/\ew/$& x 2/eg;             # yields \*(Aqaabbcc  224466xxyyzz\*(Aq\&\&    s/%(.)/$percent{$1}/g;   

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?