📄 perlref.1
字号:
A reference to an anonymous subroutine can be created by using\&\f(CW\*(C`sub\*(C'\fR without a subname:.Sp.Vb 1\& $coderef = sub { print "Boink!\en" };.Ve.SpNote the semicolon. Except for the codeinside not being immediately executed, a \f(CW\*(C`sub {}\*(C'\fR is not so much adeclaration as it is an operator, like \f(CW\*(C`do{}\*(C'\fR or \f(CW\*(C`eval{}\*(C'\fR. (However, nomatter how many times you execute that particular line (unless you're in an\&\f(CW\*(C`eval("...")\*(C'\fR), \f(CW$coderef\fR will still have a reference to the \fIsame\fRanonymous subroutine.).SpAnonymous subroutines act as closures with respect to \fImy()\fR variables,that is, variables lexically visible within the current scope. Closureis a notion out of the Lisp world that says if you define an anonymousfunction in a particular lexical context, it pretends to run in thatcontext even when it's called outside the context..SpIn human terms, it's a funny way of passing arguments to a subroutine whenyou define it as well as when you call it. It's useful for setting uplittle bits of code to run later, such as callbacks. You can evendo object-oriented stuff with it, though Perl already provides a differentmechanism to do that\*(--see perlobj..SpYou might also think of closure as a way to write a subroutinetemplate without using \fIeval()\fR. Here's a small example of howclosures work:.Sp.Vb 6\& sub newprint {\& my $x = shift;\& return sub { my $y = shift; print "$x, $y!\en"; };\& }\& $h = newprint("Howdy");\& $g = newprint("Greetings");\&\& # Time passes...\&\& &$h("world");\& &$g("earthlings");.Ve.SpThis prints.Sp.Vb 2\& Howdy, world!\& Greetings, earthlings!.Ve.SpNote particularly that \f(CW$x\fR continues to refer to the value passedinto \fInewprint()\fR \fIdespite\fR \*(L"my \f(CW$x\fR\*(R" having gone out of scope by thetime the anonymous subroutine runs. That's what a closure is allabout..SpThis applies only to lexical variables, by the way. Dynamic variablescontinue to work as they have always worked. Closure is not somethingthat most Perl programmers need trouble themselves about to begin with..IP "5." 4.IX Xref "constructor new".IX Item "5."References are often returned by special subroutines called constructors. Perlobjects are just references to a special type of object that happens to knowwhich package it's associated with. Constructors are just special subroutinesthat know how to create that association. They do so by starting with anordinary reference, and it remains an ordinary reference even while it's alsobeing an object. Constructors are often named \f(CW\*(C`new()\*(C'\fR. You \fIcan\fR call themindirectly:.Sp.Vb 1\& $objref = new Doggie( Tail => \*(Aqshort\*(Aq, Ears => \*(Aqlong\*(Aq );.Ve.SpBut that can produce ambiguous syntax in certain cases, so it's oftenbetter to use the direct method invocation approach:.Sp.Vb 1\& $objref = Doggie\->new(Tail => \*(Aqshort\*(Aq, Ears => \*(Aqlong\*(Aq);\&\& use Term::Cap;\& $terminal = Term::Cap\->Tgetent( { OSPEED => 9600 });\&\& use Tk;\& $main = MainWindow\->new();\& $menubar = $main\->Frame(\-relief => "raised",\& \-borderwidth => 2).Ve.IP "6." 4.IX Xref "autovivification".IX Item "6."References of the appropriate type can spring into existence if youdereference them in a context that assumes they exist. Because we haven'ttalked about dereferencing yet, we can't show you any examples yet..IP "7." 4.IX Xref "*foo{THING} *".IX Item "7."A reference can be created by using a special syntax, lovingly known asthe *foo{\s-1THING\s0} syntax. *foo{\s-1THING\s0} returns a reference to the \s-1THING\s0slot in *foo (which is the symbol table entry which holds everythingknown as foo)..Sp.Vb 7\& $scalarref = *foo{SCALAR};\& $arrayref = *ARGV{ARRAY};\& $hashref = *ENV{HASH};\& $coderef = *handler{CODE};\& $ioref = *STDIN{IO};\& $globref = *foo{GLOB};\& $formatref = *foo{FORMAT};.Ve.SpAll of these are self-explanatory except for \f(CW*foo{IO}\fR. It returnsthe \s-1IO\s0 handle, used for file handles (\*(L"open\*(R" in perlfunc), sockets(\*(L"socket\*(R" in perlfunc and \*(L"socketpair\*(R" in perlfunc), and directoryhandles (\*(L"opendir\*(R" in perlfunc). For compatibility with previousversions of Perl, \f(CW*foo{FILEHANDLE}\fR is a synonym for \f(CW*foo{IO}\fR, though itis deprecated as of 5.8.0. If deprecation warnings are in effect, it will warnof its use..Sp\&\f(CW*foo{THING}\fR returns undef if that particular \s-1THING\s0 hasn't been used yet,except in the case of scalars. \f(CW*foo{SCALAR}\fR returns a reference to ananonymous scalar if \f(CW$foo\fR hasn't been used yet. This might change in afuture release..Sp\&\f(CW*foo{IO}\fR is an alternative to the \f(CW*HANDLE\fR mechanism given in\&\*(L"Typeglobs and Filehandles\*(R" in perldata for passing filehandlesinto or out of subroutines, or storing into larger data structures.Its disadvantage is that it won't create a new filehandle for you.Its advantage is that you have less risk of clobbering more thanyou want to with a typeglob assignment. (It still conflates fileand directory handles, though.) However, if you assign the incomingvalue to a scalar instead of a typeglob as we do in the examplesbelow, there's no risk of that happening..Sp.Vb 2\& splutter(*STDOUT); # pass the whole glob\& splutter(*STDOUT{IO}); # pass both file and dir handles\&\& sub splutter {\& my $fh = shift;\& print $fh "her um well a hmmm\en";\& }\&\& $rec = get_rec(*STDIN); # pass the whole glob\& $rec = get_rec(*STDIN{IO}); # pass both file and dir handles\&\& sub get_rec {\& my $fh = shift;\& return scalar <$fh>;\& }.Ve.Sh "Using References".IX Xref "reference, use dereferencing dereference".IX Subsection "Using References"That's it for creating references. By now you're probably dying toknow how to use references to get back to your long-lost data. Thereare several basic methods..IP "1." 4Anywhere you'd put an identifier (or chain of identifiers) as partof a variable or subroutine name, you can replace the identifier witha simple scalar variable containing a reference of the correct type:.Sp.Vb 6\& $bar = $$scalarref;\& push(@$arrayref, $filename);\& $$arrayref[0] = "January";\& $$hashref{"KEY"} = "VALUE";\& &$coderef(1,2,3);\& print $globref "output\en";.Ve.SpIt's important to understand that we are specifically \fInot\fR dereferencing\&\f(CW$arrayref[0]\fR or \f(CW$hashref{"KEY"}\fR there. The dereference of thescalar variable happens \fIbefore\fR it does any key lookups. Anything morecomplicated than a simple scalar variable must use methods 2 or 3 below.However, a \*(L"simple scalar\*(R" includes an identifier that itself uses method1 recursively. Therefore, the following prints \*(L"howdy\*(R"..Sp.Vb 2\& $refrefref = \e\e\e"howdy";\& print $$$$refrefref;.Ve.IP "2." 4Anywhere you'd put an identifier (or chain of identifiers) as part of avariable or subroutine name, you can replace the identifier with a\&\s-1BLOCK\s0 returning a reference of the correct type. In other words, theprevious examples could be written like this:.Sp.Vb 6\& $bar = ${$scalarref};\& push(@{$arrayref}, $filename);\& ${$arrayref}[0] = "January";\& ${$hashref}{"KEY"} = "VALUE";\& &{$coderef}(1,2,3);\& $globref\->print("output\en"); # iff IO::Handle is loaded.Ve.SpAdmittedly, it's a little silly to use the curlies in this case, butthe \s-1BLOCK\s0 can contain any arbitrary expression, in particular,subscripted expressions:.Sp.Vb 1\& &{ $dispatch{$index} }(1,2,3); # call correct routine.Ve.SpBecause of being able to omit the curlies for the simple case of \f(CW$$x\fR,people often make the mistake of viewing the dereferencing symbols asproper operators, and wonder about their precedence. If they were,though, you could use parentheses instead of braces. That's not the case.Consider the difference below; case 0 is a short-hand version of case 1,\&\fInot\fR case 2:.Sp.Vb 4\& $$hashref{"KEY"} = "VALUE"; # CASE 0\& ${$hashref}{"KEY"} = "VALUE"; # CASE 1\& ${$hashref{"KEY"}} = "VALUE"; # CASE 2\& ${$hashref\->{"KEY"}} = "VALUE"; # CASE 3.Ve.SpCase 2 is also deceptive in that you're accessing a variablecalled \f(CW%hashref\fR, not dereferencing through \f(CW$hashref\fR to the hashit's presumably referencing. That would be case 3..IP "3." 4Subroutine calls and lookups of individual array elements arise oftenenough that it gets cumbersome to use method 2. As a form ofsyntactic sugar, the examples for method 2 may be written:.Sp.Vb 3\& $arrayref\->[0] = "January"; # Array element\& $hashref\->{"KEY"} = "VALUE"; # Hash element\& $coderef\->(1,2,3); # Subroutine call.Ve.SpThe left side of the arrow can be any expression returning a reference,including a previous dereference. Note that \f(CW$array[$x]\fR is \fInot\fR thesame thing as \f(CW\*(C`$array\->[$x]\*(C'\fR here:.Sp.Vb 1\& $array[$x]\->{"foo"}\->[0] = "January";.Ve.SpThis is one of the cases we mentioned earlier in which references couldspring into existence when in an lvalue context. Before thisstatement, \f(CW$array[$x]\fR may have been undefined. If so, it'sautomatically defined with a hash reference so that we can look up\&\f(CW\*(C`{"foo"}\*(C'\fR in it. Likewise \f(CW\*(C`$array[$x]\->{"foo"}\*(C'\fR will automatically getdefined with an array reference so that we can look up \f(CW\*(C`[0]\*(C'\fR in it.This process is called \fIautovivification\fR..SpOne more thing here. The arrow is optional \fIbetween\fR bracketssubscripts, so you can shrink the above down to.Sp.Vb 1\& $array[$x]{"foo"}[0] = "January";.Ve.SpWhich, in the degenerate case of using only ordinary arrays, gives youmultidimensional arrays just like C's:.Sp.Vb 1\& $score[$x][$y][$z] += 42;.Ve.SpWell, okay, not entirely like C's arrays, actually. C doesn't know howto grow its arrays on demand. Perl does..IP "4." 4If a reference happens to be a reference to an object, then there areprobably methods to access the things referred to, and you should probablystick to those methods unless you're in the class package that defines theobject's methods. In other words, be nice, and don't violate the object'sencapsulation without a very good reason. Perl does not enforceencapsulation. We are not totalitarians here. We do expect some basiccivility though..PPUsing a string or number as a reference produces a symbolic reference,as explained above. Using a reference as a number produces aninteger representing its storage location in memory. The onlyuseful thing to be done with this is to compare two referencesnumerically to see whether they refer to the same location..IX Xref "reference, numeric context".PP.Vb 3\& if ($ref1 == $ref2) { # cheap numeric compare of references\& print "refs 1 and 2 refer to the same thing\en";\& }.Ve.PPUsing a reference as a string produces both its referent's type,including any package blessing as described in perlobj, as wellas the numeric address expressed in hex. The \fIref()\fR operator returnsjust the type of thing the reference is pointing to, without the
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -