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

📄 perlref.1

📁 视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.
💻 1
📖 第 1 页 / 共 3 页
字号:
address.  See \*(L"ref\*(R" in perlfunc for details and examples of its use..IX Xref "reference, string context".PPThe \fIbless()\fR operator may be used to associate the object a referencepoints to with a package functioning as an object class.  See perlobj..PPA typeglob may be dereferenced the same way a reference can, becausethe dereference syntax always indicates the type of reference desired.So \f(CW\*(C`${*foo}\*(C'\fR and \f(CW\*(C`${\e$foo}\*(C'\fR both indicate the same scalar variable..PPHere's a trick for interpolating a subroutine call into a string:.PP.Vb 1\&    print "My sub returned @{[mysub(1,2,3)]} that time.\en";.Ve.PPThe way it works is that when the \f(CW\*(C`@{...}\*(C'\fR is seen in the double-quotedstring, it's evaluated as a block.  The block creates a reference to ananonymous array containing the results of the call to \f(CW\*(C`mysub(1,2,3)\*(C'\fR.  Sothe whole block returns a reference to an array, which is thendereferenced by \f(CW\*(C`@{...}\*(C'\fR and stuck into the double-quoted string. Thischicanery is also useful for arbitrary expressions:.PP.Vb 1\&    print "That yields @{[$n + 5]} widgets\en";.Ve.PPSimilarly, an expression that returns a reference to a scalar can bedereferenced via \f(CW\*(C`${...}\*(C'\fR. Thus, the above expression may be writtenas:.PP.Vb 1\&    print "That yields ${\e($n + 5)} widgets\en";.Ve.Sh "Symbolic references".IX Xref "reference, symbolic reference, soft symbolic reference soft reference".IX Subsection "Symbolic references"We said that references spring into existence as necessary if they areundefined, but we didn't say what happens if a value used as areference is already defined, but \fIisn't\fR a hard reference.  If youuse it as a reference, it'll be treated as a symbolicreference.  That is, the value of the scalar is taken to be the \fIname\fRof a variable, rather than a direct link to a (possibly) anonymousvalue..PPPeople frequently expect it to work like this.  So it does..PP.Vb 9\&    $name = "foo";\&    $$name = 1;                 # Sets $foo\&    ${$name} = 2;               # Sets $foo\&    ${$name x 2} = 3;           # Sets $foofoo\&    $name\->[0] = 4;             # Sets $foo[0]\&    @$name = ();                # Clears @foo\&    &$name();                   # Calls &foo() (as in Perl 4)\&    $pack = "THAT";\&    ${"${pack}::$name"} = 5;    # Sets $THAT::foo without eval.Ve.PPThis is powerful, and slightly dangerous, in that it's possibleto intend (with the utmost sincerity) to use a hard reference, andaccidentally use a symbolic reference instead.  To protect againstthat, you can say.PP.Vb 1\&    use strict \*(Aqrefs\*(Aq;.Ve.PPand then only hard references will be allowed for the rest of the enclosingblock.  An inner block may countermand that with.PP.Vb 1\&    no strict \*(Aqrefs\*(Aq;.Ve.PPOnly package variables (globals, even if localized) are visible tosymbolic references.  Lexical variables (declared with \fImy()\fR) aren't ina symbol table, and thus are invisible to this mechanism.  For example:.PP.Vb 6\&    local $value = 10;\&    $ref = "value";\&    {\&        my $value = 20;\&        print $$ref;\&    }.Ve.PPThis will still print 10, not 20.  Remember that \fIlocal()\fR affects packagevariables, which are all \*(L"global\*(R" to the package..Sh "Not-so-symbolic references".IX Subsection "Not-so-symbolic references"A new feature contributing to readability in perl version 5.001 is that thebrackets around a symbolic reference behave more like quotes, just as theyalways have within a string.  That is,.PP.Vb 2\&    $push = "pop on ";\&    print "${push}over";.Ve.PPhas always meant to print \*(L"pop on over\*(R", even though push isa reserved word.  This has been generalized to work the same outsideof quotes, so that.PP.Vb 1\&    print ${push} . "over";.Ve.PPand even.PP.Vb 1\&    print ${ push } . "over";.Ve.PPwill have the same effect.  (This would have been a syntax error inPerl 5.000, though Perl 4 allowed it in the spaceless form.)  Thisconstruct is \fInot\fR considered to be a symbolic reference when you'reusing strict refs:.PP.Vb 3\&    use strict \*(Aqrefs\*(Aq;\&    ${ bareword };      # Okay, means $bareword.\&    ${ "bareword" };    # Error, symbolic reference..Ve.PPSimilarly, because of all the subscripting that is done using singlewords, we've applied the same rule to any bareword that is used forsubscripting a hash.  So now, instead of writing.PP.Vb 1\&    $array{ "aaa" }{ "bbb" }{ "ccc" }.Ve.PPyou can write just.PP.Vb 1\&    $array{ aaa }{ bbb }{ ccc }.Ve.PPand not worry about whether the subscripts are reserved words.  In therare event that you do wish to do something like.PP.Vb 1\&    $array{ shift }.Ve.PPyou can force interpretation as a reserved word by adding anything thatmakes it more than a bareword:.PP.Vb 3\&    $array{ shift() }\&    $array{ +shift }\&    $array{ shift @_ }.Ve.PPThe \f(CW\*(C`use warnings\*(C'\fR pragma or the \fB\-w\fR switch will warn you if itinterprets a reserved word as a string.But it will no longer warn you about using lowercase words, because thestring is effectively quoted..Sh "Pseudo-hashes: Using an array as a hash".IX Xref "pseudo-hash pseudo hash pseudohash".IX Subsection "Pseudo-hashes: Using an array as a hash"Pseudo-hashes have been removed from Perl.  The 'fields' pragmaremains available..Sh "Function Templates".IX Xref "scope, lexical closure lexical lexical scope subroutine, nested sub, nested subroutine, local sub, local".IX Subsection "Function Templates"As explained above, an anonymous function with access to the lexicalvariables visible when that function was compiled, creates a closure.  Itretains access to those variables even though it doesn't get run untillater, such as in a signal handler or a Tk callback..PPUsing a closure as a function template allows us to generate many functionsthat act similarly.  Suppose you wanted functions named after the colorsthat generated \s-1HTML\s0 font changes for the various colors:.PP.Vb 1\&    print "Be ", red("careful"), "with that ", green("light");.Ve.PPThe \fIred()\fR and \fIgreen()\fR functions would be similar.  To create these,we'll assign a closure to a typeglob of the name of the function we'retrying to build..PP.Vb 5\&    @colors = qw(red blue green yellow orange purple violet);\&    for my $name (@colors) {\&        no strict \*(Aqrefs\*(Aq;       # allow symbol table manipulation\&        *$name = *{uc $name} = sub { "<FONT COLOR=\*(Aq$name\*(Aq>@_</FONT>" };\&    }.Ve.PPNow all those different functions appear to exist independently.  You cancall \fIred()\fR, \s-1\fIRED\s0()\fR, \fIblue()\fR, \s-1\fIBLUE\s0()\fR, \fIgreen()\fR, etc.  This technique saves onboth compile time and memory use, and is less error-prone as well, sincesyntax checks happen at compile time.  It's critical that any variables inthe anonymous subroutine be lexicals in order to create a proper closure.That's the reasons for the \f(CW\*(C`my\*(C'\fR on the loop iteration variable..PPThis is one of the only places where giving a prototype to a closure makesmuch sense.  If you wanted to impose scalar context on the arguments ofthese functions (probably not a wise idea for this particular example),you could have written it this way instead:.PP.Vb 1\&    *$name = sub ($) { "<FONT COLOR=\*(Aq$name\*(Aq>$_[0]</FONT>" };.Ve.PPHowever, since prototype checking happens at compile time, the assignmentabove happens too late to be of much use.  You could address this byputting the whole loop of assignments within a \s-1BEGIN\s0 block, forcing itto occur during compilation..PPAccess to lexicals that change over time\*(--like those in the \f(CW\*(C`for\*(C'\fR loopabove, basically aliases to elements from the surrounding lexical scopes\*(--only works with anonymous subs, not with named subroutines. Generallysaid, named subroutines do not nest properly and should only be declaredin the main package scope..PPThis is because named subroutines are created at compile time so theirlexical variables get assigned to the parent lexicals from the firstexecution of the parent block. If a parent scope is entered a secondtime, its lexicals are created again, while the nested subs stillreference the old ones..PPAnonymous subroutines get to capture each time you execute the \f(CW\*(C`sub\*(C'\fRoperator, as they are created on the fly. If you are accustomed to usingnested subroutines in other programming languages with their own privatevariables, you'll have to work at it a bit in Perl.  The intuitive codingof this type of thing incurs mysterious warnings about \*(L"will not stayshared\*(R" due to the reasons explained above. For example, this won't work:.PP.Vb 5\&    sub outer {\&        my $x = $_[0] + 35;\&        sub inner { return $x * 19 }   # WRONG\&        return $x + inner();\&    }.Ve.PPA work-around is the following:.PP.Vb 5\&    sub outer {\&        my $x = $_[0] + 35;\&        local *inner = sub { return $x * 19 };\&        return $x + inner();\&    }.Ve.PPNow \fIinner()\fR can only be called from within \fIouter()\fR, because of thetemporary assignments of the anonymous subroutine. But when it does,it has normal access to the lexical variable \f(CW$x\fR from the scope of\&\fIouter()\fR at the time outer is invoked..PPThis has the interesting effect of creating a function local to anotherfunction, something not normally supported in Perl..SH "WARNING".IX Xref "reference, string context reference, use as hash key".IX Header "WARNING"You may not (usefully) use a reference as the key to a hash.  It will beconverted into a string:.PP.Vb 1\&    $x{ \e$a } = $a;.Ve.PPIf you try to dereference the key, it won't do a hard dereference, andyou won't accomplish what you're attempting.  You might want to do somethingmore like.PP.Vb 2\&    $r = \e@a;\&    $x{ $r } = $r;.Ve.PPAnd then at least you can use the \fIvalues()\fR, which will bereal refs, instead of the \fIkeys()\fR, which won't..PPThe standard Tie::RefHash module provides a convenient workaround to this..SH "SEE ALSO".IX Header "SEE ALSO"Besides the obvious documents, source code can be instructive.Some pathological examples of the use of references can be foundin the \fIt/op/ref.t\fR regression test in the Perl source directory..PPSee also perldsc and perllol for how to use references to createcomplex data structures, and perltoot, perlobj, and perlbotfor how to use them to create objects.

⌨️ 快捷键说明

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