⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 perlfaq7.1

📁 视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.
💻 1
📖 第 1 页 / 共 4 页
字号:
just such situations as the one above..PPAnother operator with surprising precedence is exponentiation.  Itbinds more tightly even than unary minus, making \f(CW\*(C`\-2**2\*(C'\fR product anegative not a positive four.  It is also right-associating, meaningthat \f(CW\*(C`2**3**2\*(C'\fR is two raised to the ninth power, not eight squared..PPAlthough it has the same precedence as in C, Perl's \f(CW\*(C`?:\*(C'\fR operatorproduces an lvalue.  This assigns \f(CW$x\fR to either \f(CW$a\fR or \f(CW$b\fR, dependingon the trueness of \f(CW$maybe:\fR.PP.Vb 1\&        ($maybe ? $a : $b) = $x;.Ve.Sh "How do I declare/create a structure?".IX Subsection "How do I declare/create a structure?"In general, you don't \*(L"declare\*(R" a structure.  Just use a (probablyanonymous) hash reference.  See perlref and perldsc for details.Here's an example:.PP.Vb 3\&        $person = {};                   # new anonymous hash\&        $person\->{AGE}  = 24;           # set field AGE to 24\&        $person\->{NAME} = "Nat";        # set field NAME to "Nat".Ve.PPIf you're looking for something a bit more rigorous, try perltoot..Sh "How do I create a module?".IX Subsection "How do I create a module?"(contributed by brian d foy).PPperlmod, perlmodlib, perlmodstyle explain modulesin all the gory details. perlnewmod gives a briefoverview of the process along with a couple of suggestionsabout style..PPIf you need to include C code or C library interfaces inyour module, you'll need h2xs.  h2xs will create the moduledistribution structure and the initial interface filesyou'll need.  perlxs and perlxstut explain the details..PPIf you don't need to use C code, other tools such asExtUtils::ModuleMaker and Module::Starter, can help youcreate a skeleton module distribution..PPYou may also want to see Sam Tregar's \*(L"Writing Perl Modulesfor \s-1CPAN\s0\*(R" ( http://apress.com/book/bookDisplay.html?bID=14 )which is the best hands-on guide to creating moduledistributions..Sh "How do I adopt or take over a module already on \s-1CPAN\s0?".IX Subsection "How do I adopt or take over a module already on CPAN?"(contributed by brian d foy).PPThe easiest way to take over a module is to have the currentmodule maintainer either make you a co-maintainer or transferthe module to you..PPIf you can't reach the author for some reason (e.g. email bounces),the \s-1PAUSE\s0 admins at modules@perl.org can help. The \s-1PAUSE\s0 adminstreat each case individually..IP "\(bu" 4Get a login for the Perl Authors Upload Server (\s-1PAUSE\s0) if you don'talready have one: http://pause.perl.org.IP "\(bu" 4Write to modules@perl.org explaining what you did to contact thecurrent maintainer. The \s-1PAUSE\s0 admins will also try to reach themaintainer..IP "\(bu" 4Post a public message in a heavily trafficked site announcing yourintention to take over the module..IP "\(bu" 4Wait a bit. The \s-1PAUSE\s0 admins don't want to act too quickly in casethe current maintainer is on holiday. If there's no response to private communication or the public post, a \s-1PAUSE\s0 admin can transferit to you..Sh "How do I create a class?".IX Subsection "How do I create a class?"See perltoot for an introduction to classes and objects, as well asperlobj and perlbot..Sh "How can I tell if a variable is tainted?".IX Subsection "How can I tell if a variable is tainted?"You can use the \fItainted()\fR function of the Scalar::Util module, availablefrom \s-1CPAN\s0 (or included with Perl since release 5.8.0).See also \*(L"Laundering and Detecting Tainted Data\*(R" in perlsec..Sh "What's a closure?".IX Subsection "What's a closure?"Closures are documented in perlref..PP\&\fIClosure\fR is a computer science term with a precise buthard-to-explain meaning. Usually, closures are implemented in Perl asanonymous subroutines with lasting references to lexical variablesoutside their own scopes. These lexicals magically refer to thevariables that were around when the subroutine was defined (deep binding)..PPClosures are most often used in programming languages where you canhave the return value of a function be itself a function, as you canin Perl. Note that some languages provide anonymous functions but arenot capable of providing proper closures: the Python language, forexample.  For more information on closures, check out any textbook onfunctional programming.  Scheme is a language that not only supportsbut encourages closures..PPHere's a classic non-closure function-generating function:.PP.Vb 3\&        sub add_function_generator {\&                return sub { shift() + shift() };\&                }\&\&        $add_sub = add_function_generator();\&        $sum = $add_sub\->(4,5);                # $sum is 9 now..Ve.PPThe anonymous subroutine returned by \fIadd_function_generator()\fR isn'ttechnically a closure because it refers to no lexicals outside its ownscope.  Using a closure gives you a \fIfunction template\fR with somecustomization slots left out to be filled later..PPContrast this with the following \fImake_adder()\fR function, in which thereturned anonymous function contains a reference to a lexical variableoutside the scope of that function itself.  Such a reference requiresthat Perl return a proper closure, thus locking in for all time thevalue that the lexical had when the function was created..PP.Vb 4\&        sub make_adder {\&                my $addpiece = shift;\&                return sub { shift() + $addpiece };\&        }\&        \&        $f1 = make_adder(20);\&        $f2 = make_adder(555);.Ve.PPNow \f(CW\*(C`&$f1($n)\*(C'\fR is always 20 plus whatever \f(CW$n\fR you pass in, whereas\&\f(CW\*(C`&$f2($n)\*(C'\fR is always 555 plus whatever \f(CW$n\fR you pass in.  The \f(CW$addpiece\fRin the closure sticks around..PPClosures are often used for less esoteric purposes.  For example, whenyou want to pass in a bit of code into a function:.PP.Vb 2\&        my $line;\&        timeout( 30, sub { $line = <STDIN> } );.Ve.PPIf the code to execute had been passed in as a string,\&\f(CW\*(Aq$line = <STDIN>\*(Aq\fR, there would have been no way for thehypothetical \fItimeout()\fR function to access the lexical variable\&\f(CW$line\fR back in its caller's scope..PPAnother use for a closure is to make a variable \fIprivate\fR to anamed subroutine, e.g. a counter that gets initialized at creationtime of the sub and can only be modified from within the sub.This is sometimes used with a \s-1BEGIN\s0 block in package files to makesure a variable doesn't get meddled with during the lifetime of thepackage:.PP.Vb 4\&        BEGIN {\&                my $id = 0;\&                sub next_id { ++$id }\&        }.Ve.PPThis is discussed in more detail in perlsub, see the entry on\&\fIPersistent Private Variables\fR..Sh "What is variable suicide and how can I prevent it?".IX Subsection "What is variable suicide and how can I prevent it?"This problem was fixed in perl 5.004_05, so preventing it means upgradingyour version of perl. ;).PPVariable suicide is when you (temporarily or permanently) lose the valueof a variable.  It is caused by scoping through \fImy()\fR and \fIlocal()\fRinteracting with either closures or aliased \fIforeach()\fR iterator variablesand subroutine arguments.  It used to be easy to inadvertently lose avariable's value this way, but now it's much harder.  Take this code:.PP.Vb 4\&        my $f = \*(Aqfoo\*(Aq;\&        sub T {\&                while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\en" }\&                }\&\&        T;\&        print "Finally $f\en";.Ve.PPIf you are experiencing variable suicide, that \f(CW\*(C`my $f\*(C'\fR in the subroutinedoesn't pick up a fresh copy of the \f(CW$f\fR whose value is <foo>. The outputshows that inside the subroutine the value of \f(CW$f\fR leaks through when itshouldn't, as in this output:.PP.Vb 4\&        foobar\&        foobarbar\&        foobarbarbar\&        Finally foo.Ve.PPThe \f(CW$f\fR that has \*(L"bar\*(R" added to it three times should be a new \f(CW$f\fR\&\f(CW\*(C`my $f\*(C'\fR should create a new lexical variable each time through the loop.The expected output is:.PP.Vb 4\&        foobar\&        foobar\&        foobar\&        Finally foo.Ve.Sh "How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?".IX Subsection "How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?"With the exception of regexes, you need to pass references to theseobjects.  See \*(L"Pass by Reference\*(R" in perlsub for this particularquestion, and perlref for information on references..PPSee \*(L"Passing Regexes\*(R", later in perlfaq7, for information onpassing regular expressions..IP "Passing Variables and Functions" 4.IX Item "Passing Variables and Functions"Regular variables and functions are quite easy to pass: just pass in areference to an existing or anonymous variable or function:.Sp.Vb 1\&        func( \e$some_scalar );\&\&        func( \e@some_array  );\&        func( [ 1 .. 10 ]   );\&\&        func( \e%some_hash   );\&        func( { this => 10, that => 20 }   );\&\&        func( \e&some_func   );\&        func( sub { $_[0] ** $_[1] }   );.Ve.IP "Passing Filehandles" 4.IX Item "Passing Filehandles"As of Perl 5.6, you can represent filehandles with scalar variableswhich you treat as any other scalar..Sp.Vb 2\&        open my $fh, $filename or die "Cannot open $filename! $!";\&        func( $fh );\&\&        sub func {\&                my $passed_fh = shift;\&\&                my $line = <$passed_fh>;\&                }.Ve.SpBefore Perl 5.6, you had to use the \f(CW*FH\fR or \f(CW\*(C`\e*FH\*(C'\fR notations.These are \*(L"typeglobs\*(R"\-\-see \*(L"Typeglobs and Filehandles\*(R" in perldataand especially \*(L"Pass by Reference\*(R" in perlsub for more information..IP "Passing Regexes" 4.IX Item "Passing Regexes"To pass regexes around, you'll need to be using a release of Perlsufficiently recent as to support the \f(CW\*(C`qr//\*(C'\fR construct, pass aroundstrings and use an exception-trapping eval, or else be very, very clever..SpHere's an example of how to pass in a string to be regex comparedusing \f(CW\*(C`qr//\*(C'\fR:.Sp.Vb 6\&        sub compare($$) {\&                my ($val1, $regex) = @_;\&                my $retval = $val1 =~ /$regex/;\&        return $retval;\&        }\&        $match = compare("old McDonald", qr/d.*D/i);.Ve.SpNotice how \f(CW\*(C`qr//\*(C'\fR allows flags at the end.  That pattern was compiledat compile time, although it was executed later.  The nifty \f(CW\*(C`qr//\*(C'\fRnotation wasn't introduced until the 5.005 release.  Before that, youhad to approach this problem much less intuitively.  For example, hereit is again if you don't have \f(CW\*(C`qr//\*(C'\fR:.Sp.Vb 6\&        sub compare($$) {\&                my ($val1, $regex) = @_;\&                my $retval = eval { $val1 =~ /$regex/ };\&        die if $@;\&        return $retval;\&        }\&\&        $match = compare("old McDonald", q/($?i)d.*D/);.Ve.SpMake sure you never say something like this:.Sp.Vb 1\&        return eval "\e$val =~ /$regex/";   # WRONG.Ve.Spor someone can sneak shell escapes into the regex due to the doubleinterpolation of the eval and the double-quoted string.  For example:.Sp.Vb 1\&        $pattern_of_evil = \*(Aqdanger ${ system("rm \-rf * &") } danger\*(Aq;\&\&        eval "\e$string =~ /$pattern_of_evil/";.Ve.SpThose preferring to be very, very clever might see the O'Reilly book,\&\fIMastering Regular Expressions\fR, by Jeffrey Friedl.  Page 273's\&\fIBuild_MatchMany_Function()\fR is particularly interesting.  A complete

⌨️ 快捷键说明

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