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

📄 perlfaq7.1

📁 视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.
💻 1
📖 第 1 页 / 共 4 页
字号:
citation of this book is given in perlfaq2..IP "Passing Methods" 4.IX Item "Passing Methods"To pass an object method into a subroutine, you can do this:.Sp.Vb 7\&        call_a_lot(10, $some_obj, "methname")\&        sub call_a_lot {\&                my ($count, $widget, $trick) = @_;\&                for (my $i = 0; $i < $count; $i++) {\&                        $widget\->$trick();\&                }\&        }.Ve.SpOr, you can use a closure to bundle up the object, itsmethod call, and arguments:.Sp.Vb 6\&        my $whatnot =  sub { $some_obj\->obfuscate(@args) };\&        func($whatnot);\&        sub func {\&                my $code = shift;\&                &$code();\&        }.Ve.SpYou could also investigate the \fIcan()\fR method in the \s-1UNIVERSAL\s0 class(part of the standard perl distribution)..Sh "How do I create a static variable?".IX Subsection "How do I create a static variable?"(contributed by brian d foy).PPPerl doesn't have \*(L"static\*(R" variables, which can only be accessed fromthe function in which they are declared. You can get the same effectwith lexical variables, though..PPYou can fake a static variable by using a lexical variable which goesout of scope. In this example, you define the subroutine \f(CW\*(C`counter\*(C'\fR, andit uses the lexical variable \f(CW$count\fR. Since you wrap this in a \s-1BEGIN\s0block, \f(CW$count\fR is defined at compile-time, but also goes out ofscope at the end of the \s-1BEGIN\s0 block. The \s-1BEGIN\s0 block also ensures thatthe subroutine and the value it uses is defined at compile-time so thesubroutine is ready to use just like any other subroutine, and you canput this code in the same place as other subroutines in the programtext (i.e. at the end of the code, typically). The subroutine\&\f(CW\*(C`counter\*(C'\fR still has a reference to the data, and is the only way youcan access the value (and each time you do, you increment the value).The data in chunk of memory defined by \f(CW$count\fR is private to\&\f(CW\*(C`counter\*(C'\fR..PP.Vb 4\&        BEGIN {\&                my $count = 1;\&                sub counter { $count++ }\&        }\&        \&        my $start = counter();\&        \&        .... # code that calls counter();\&        \&        my $end = counter();.Ve.PPIn the previous example, you created a function-private variablebecause only one function remembered its reference. You could definemultiple functions while the variable is in scope, and each functioncan share the \*(L"private\*(R" variable. It's not really \*(L"static\*(R" because youcan access it outside the function while the lexical variable is inscope, and even create references to it. In this example,\&\f(CW\*(C`increment_count\*(C'\fR and \f(CW\*(C`return_count\*(C'\fR share the variable. Onefunction adds to the value and the other simply returns the value.They can both access \f(CW$count\fR, and since it has gone out of scope,there is no other way to access it..PP.Vb 5\&        BEGIN {\&                my $count = 1;\&                sub increment_count { $count++ }\&                sub return_count    { $count }\&        }.Ve.PPTo declare a file-private variable, you still use a lexical variable.A file is also a scope, so a lexical variable defined in the filecannot be seen from any other file..PPSee \*(L"Persistent Private Variables\*(R" in perlsub for more information.The discussion of closures in perlref may help you even though wedid not use anonymous subroutines in this answer. See\&\*(L"Persistent Private Variables\*(R" in perlsub for details..Sh "What's the difference between dynamic and lexical (static) scoping?  Between \fIlocal()\fP and \fImy()\fP?".IX Subsection "What's the difference between dynamic and lexical (static) scoping?  Between local() and my()?"\&\f(CW\*(C`local($x)\*(C'\fR saves away the old value of the global variable \f(CW$x\fRand assigns a new value for the duration of the subroutine \fIwhich isvisible in other functions called from that subroutine\fR.  This is doneat run-time, so is called dynamic scoping.  \fIlocal()\fR always affects globalvariables, also called package variables or dynamic variables..PP\&\f(CW\*(C`my($x)\*(C'\fR creates a new variable that is only visible in the currentsubroutine.  This is done at compile-time, so it is called lexical orstatic scoping.  \fImy()\fR always affects private variables, also calledlexical variables or (improperly) static(ly scoped) variables..PPFor instance:.PP.Vb 3\&        sub visible {\&                print "var has value $var\en";\&                }\&        \&        sub dynamic {\&                local $var = \*(Aqlocal\*(Aq;   # new temporary value for the still\-global\&                visible();              #   variable called $var\&                }\&        \&        sub lexical {\&                my $var = \*(Aqprivate\*(Aq;    # new private variable, $var\&                visible();              # (invisible outside of sub scope)\&                }\&        \&        $var = \*(Aqglobal\*(Aq;\&        \&        visible();                      # prints global\&        dynamic();                      # prints local\&        lexical();                      # prints global.Ve.PPNotice how at no point does the value \*(L"private\*(R" get printed.  That'sbecause \f(CW$var\fR only has that value within the block of the \fIlexical()\fRfunction, and it is hidden from called subroutine..PPIn summary, \fIlocal()\fR doesn't make what you think of as private, localvariables.  It gives a global variable a temporary value.  \fImy()\fR iswhat you're looking for if you want private variables..PPSee \*(L"Private Variables via \fImy()\fR\*(R" in perlsub and\&\*(L"Temporary Values via \fIlocal()\fR\*(R" in perlsub for excruciating details..Sh "How can I access a dynamic variable while a similarly named lexical is in scope?".IX Subsection "How can I access a dynamic variable while a similarly named lexical is in scope?"If you know your package, you can just mention it explicitly, as in\&\f(CW$Some_Pack::var\fR. Note that the notation \f(CW$::var\fR is \fBnot\fR the dynamic \f(CW$var\fRin the current package, but rather the one in the \*(L"main\*(R" package, asthough you had written \f(CW$main::var\fR..PP.Vb 3\&        use vars \*(Aq$var\*(Aq;\&        local $var = "global";\&        my    $var = "lexical";\&\&        print "lexical is $var\en";\&        print "global  is $main::var\en";.Ve.PPAlternatively you can use the compiler directive \fIour()\fR to bring adynamic variable into the current lexical scope..PP.Vb 2\&        require 5.006; # our() did not exist before 5.6\&        use vars \*(Aq$var\*(Aq;\&\&        local $var = "global";\&        my $var    = "lexical";\&\&        print "lexical is $var\en";\&\&        {\&                our $var;\&                print "global  is $var\en";\&        }.Ve.Sh "What's the difference between deep and shallow binding?".IX Subsection "What's the difference between deep and shallow binding?"In deep binding, lexical variables mentioned in anonymous subroutinesare the same ones that were in scope when the subroutine was created.In shallow binding, they are whichever variables with the same nameshappen to be in scope when the subroutine is called.  Perl always usesdeep binding of lexical variables (i.e., those created with \fImy()\fR).However, dynamic variables (aka global, local, or package variables)are effectively shallowly bound.  Consider this just one more reasonnot to use them.  See the answer to \*(L"What's a closure?\*(R"..ie n .Sh "Why doesn't ""my($foo) = <\s-1FILE\s0>;"" work right?".el .Sh "Why doesn't ``my($foo) = <\s-1FILE\s0>;'' work right?".IX Subsection "Why doesn't my($foo) = <FILE>; work right?"\&\f(CW\*(C`my()\*(C'\fR and \f(CW\*(C`local()\*(C'\fR give list context to the right hand sideof \f(CW\*(C`=\*(C'\fR.  The <\s-1FH\s0> read operation, like so many of Perl'sfunctions and operators, can tell which context it was called in andbehaves appropriately.  In general, the \fIscalar()\fR function can help.This function does nothing to the data itself (contrary to popular myth)but rather tells its argument to behave in whatever its scalar fashion is.If that function doesn't have a defined scalar behavior, this of coursedoesn't help you (such as with \fIsort()\fR)..PPTo enforce scalar context in this particular case, however, you needmerely omit the parentheses:.PP.Vb 3\&        local($foo) = <FILE>;       # WRONG\&        local($foo) = scalar(<FILE>);   # ok\&        local $foo  = <FILE>;       # right.Ve.PPYou should probably be using lexical variables anyway, although theissue is the same here:.PP.Vb 2\&        my($foo) = <FILE>;      # WRONG\&        my $foo  = <FILE>;      # right.Ve.Sh "How do I redefine a builtin function, operator, or method?".IX Subsection "How do I redefine a builtin function, operator, or method?"Why do you want to do that? :\-).PPIf you want to override a predefined function, such as \fIopen()\fR,then you'll have to import the new definition from a differentmodule.  See \*(L"Overriding Built-in Functions\*(R" in perlsub.  There'salso an example in \*(L"Class::Template\*(R" in perltoot..PPIf you want to overload a Perl operator, such as \f(CW\*(C`+\*(C'\fR or \f(CW\*(C`**\*(C'\fR,then you'll want to use the \f(CW\*(C`use overload\*(C'\fR pragma, documentedin overload..PPIf you're talking about obscuring method calls in parent classes,see \*(L"Overridden Methods\*(R" in perltoot..Sh "What's the difference between calling a function as &foo and \fIfoo()\fP?".IX Subsection "What's the difference between calling a function as &foo and foo()?"When you call a function as \f(CW&foo\fR, you allow that function access toyour current \f(CW@_\fR values, and you bypass prototypes.The function doesn't get an empty \f(CW@_\fR\-\-it gets yours!  While notstrictly speaking a bug (it's documented that way in perlsub), itwould be hard to consider this a feature in most cases..PPWhen you call your function as \f(CW\*(C`&foo()\*(C'\fR, then you \fIdo\fR get a new \f(CW@_\fR,but prototyping is still circumvented..PPNormally, you want to call a function using \f(CW\*(C`foo()\*(C'\fR.  You may onlyomit the parentheses if the function is already known to the compilerbecause it already saw the definition (\f(CW\*(C`use\*(C'\fR but not \f(CW\*(C`require\*(C'\fR),or via a forward reference or \f(CW\*(C`use subs\*(C'\fR declaration.  Even in thiscase, you get a clean \f(CW@_\fR without any of the old values leaking throughwhere they don't belong..Sh "How do I create a switch or case statement?".IX Subsection "How do I create a switch or case statement?"If one wants to use pure Perl and to be compatible with Perl versionsprior to 5.10, the general answer is to write a construct like this:.PP.Vb 6\&        for ($variable_to_test) {\&                if    (/pat1/)  { }     # do something\&                elsif (/pat2/)  { }     # do something else\&                elsif (/pat3/)  { }     # do something else\&                else            { }     # default\&                }.Ve.PPHere's a simple example of a switch based on pattern matching,lined up in a way to make it look more like a switch statement.We'll do a multiway conditional based on the type of reference storedin \f(CW$whatchamacallit:\fR.PP.Vb 1\&    SWITCH: for (ref $whatchamacallit) {\&\&        /^$/            && die "not a reference";\&\&        /SCALAR/        && do {\&                                print_scalar($$ref);\&                                last SWITCH;\&                        };\&\&        /ARRAY/         && do {\&                                print_array(@$ref);\&                                last SWITCH;\&                        };\&\&        /HASH/          && do {\&                                print_hash(%$ref);\&                                last SWITCH;\&                        };\&\&        /CODE/          && do {\&                                warn "can\*(Aqt print function ref";\&                                last SWITCH;\&                        };\&\&        # DEFAULT\&\&        warn "User defined type skipped";\&\&    }.Ve.PPSee perlsyn for other examples in this style..PPSometimes you should change the positions of the constant and the variable.For example, let's say you wanted to test which of many answers you weregiven, but in a case-insensitive way that also allows abbreviations.You can use the following technique if the strings all start withdifferent characters or if you want to arrange the matches so thatone takes precedence over another, as \f(CW"SEND"\fR has precedence over\&\f(CW"STOP"\fR here:.PP.Vb 6\&        chomp($answer = <>);\&        if    ("SEND"  =~ /^\eQ$answer/i) { print "Action is send\en"  }\&        elsif ("STOP"  =~ /^\eQ$answer/i) { print "Action is stop\en"  }\&        elsif ("ABORT" =~ /^\eQ$answer/i) { print "Action is abort\en" }\&        elsif ("LIST"  =~ /^\eQ$answer/i) { print "Action is list\en"  }

⌨️ 快捷键说明

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