perlref.pod

来自「MSYS在windows下模拟了一个类unix的终端」· POD 代码 · 共 704 行 · 第 1/2 页

POD
704
字号
=head1 NAMEperlref - Perl references and nested data structures=head1 NOTEThis is complete documentation about all aspects of references.For a shorter, tutorial introduction to just the essential features,see L<perlreftut>.=head1 DESCRIPTIONBefore release 5 of Perl it was difficult to represent complex datastructures, because all references had to be symbolic--and even thenit was difficult to refer to a variable instead of a symbol table entry.Perl now not only makes it easier to use symbolic references to variables,but also lets you have "hard" references to any piece of data or code.Any scalar may hold a hard reference.  Because arrays and hashes containscalars, you can now easily build arrays of arrays, arrays of hashes,hashes of arrays, arrays of hashes of functions, and so on.Hard references are smart--they keep track of reference counts for you,automatically freeing the thing referred to when its reference count goesto zero.  (Reference counts for values in self-referential orcyclic data structures may not go to zero without a little help; seeL<perlobj/"Two-Phased Garbage Collection"> for a detailed explanation.)If that thing happens to be an object, the object is destructed.  SeeL<perlobj> for more about objects.  (In a sense, everything in Perl is anobject, but we usually reserve the word for references to objects thathave been officially "blessed" into a class package.)Symbolic references are names of variables or other objects, just as asymbolic link in a Unix filesystem contains merely the name of a file.The C<*glob> notation is something of a of symbolic reference.  (Symbolicreferences are sometimes called "soft references", but please don't callthem that; references are confusing enough without useless synonyms.)In contrast, hard references are more like hard links in a Unix filesystem: They are used to access an underlying object without concern forwhat its (other) name is.  When the word "reference" is used without anadjective, as in the following paragraph, it is usually talking about ahard reference.References are easy to use in Perl.  There is just one overridingprinciple: Perl does no implicit referencing or dereferencing.  When ascalar is holding a reference, it always behaves as a simple scalar.  Itdoesn't magically start being an array or hash or subroutine; you have totell it explicitly to do so, by dereferencing it.=head2 Making ReferencesReferences can be created in several ways.=over 4=item 1.By using the backslash operator on a variable, subroutine, or value.(This works much like the & (address-of) operator in C.)  This typically creates I<another> reference to a variable, becausethere's already a reference to the variable in the symbol table.  Butthe symbol table reference might go away, and you'll still have thereference that the backslash returned.  Here are some examples:    $scalarref = \$foo;    $arrayref  = \@ARGV;    $hashref   = \%ENV;    $coderef   = \&handler;    $globref   = \*foo;It isn't possible to create a true reference to an IO handle (filehandleor dirhandle) using the backslash operator.  The most you can get is areference to a typeglob, which is actually a complete symbol table entry.But see the explanation of the C<*foo{THING}> syntax below.  However,you can still use type globs and globrefs as though they were IO handles.=item 2.A reference to an anonymous array can be created using squarebrackets:    $arrayref = [1, 2, ['a', 'b', 'c']];Here we've created a reference to an anonymous array of three elementswhose final element is itself a reference to another anonymous array of threeelements.  (The multidimensional syntax described later can be used toaccess this.  For example, after the above, C<< $arrayref->[2][1] >> would havethe value "b".)Taking a reference to an enumerated list is not the sameas using square brackets--instead it's the same as creatinga list of references!    @list = (\$a, \@b, \%c);    @list = \($a, @b, %c);	# same thing!As a special case, C<\(@foo)> returns a list of references to the contentsof C<@foo>, not a reference to C<@foo> itself.  Likewise for C<%foo>,except that the key references are to copies (since the keys are juststrings rather than full-fledged scalars).=item 3.A reference to an anonymous hash can be created using curlybrackets:    $hashref = {	'Adam'  => 'Eve',	'Clyde' => 'Bonnie',    };Anonymous hash and array composers like these can be intermixed freely toproduce as complicated a structure as you want.  The multidimensionalsyntax described below works for these too.  The values above areliterals, but variables and expressions would work just as well, becauseassignment operators in Perl (even within local() or my()) are executablestatements, not compile-time declarations.Because curly brackets (braces) are used for several other thingsincluding BLOCKs, you may occasionally have to disambiguate braces at thebeginning of a statement by putting a C<+> or a C<return> in front sothat Perl realizes the opening brace isn't starting a BLOCK.  The economy andmnemonic value of using curlies is deemed worth this occasional extrahassle.For example, if you wanted a function to make a new hash and return areference to it, you have these options:    sub hashem {        { @_ } }   # silently wrong    sub hashem {       +{ @_ } }   # ok    sub hashem { return { @_ } }   # okOn the other hand, if you want the other meaning, you can do this:    sub showem {        { @_ } }   # ambiguous (currently ok, but may change)    sub showem {       {; @_ } }   # ok    sub showem { { return @_ } }   # okThe leading C<+{> and C<{;> always serve to disambiguatethe expression to mean either the HASH reference, or the BLOCK.=item 4.A reference to an anonymous subroutine can be created by usingC<sub> without a subname:    $coderef = sub { print "Boink!\n" };Note the semicolon.  Except for the codeinside not being immediately executed, a C<sub {}> is not so much adeclaration as it is an operator, like C<do{}> or C<eval{}>.  (However, nomatter how many times you execute that particular line (unless you're in anC<eval("...")>), $coderef will still have a reference to the I<same>anonymous subroutine.)Anonymous subroutines act as closures with respect to my() 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.In 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 L<perlobj>.You might also think of closure as a way to write a subroutinetemplate without using eval().  Here's a small example of howclosures work:    sub newprint {	my $x = shift;	return sub { my $y = shift; print "$x, $y!\n"; };    }    $h = newprint("Howdy");    $g = newprint("Greetings");    # Time passes...    &$h("world");    &$g("earthlings");This prints    Howdy, world!    Greetings, earthlings!Note particularly that $x continues to refer to the value passedinto newprint() I<despite> "my $x" having gone out of scope by thetime the anonymous subroutine runs.  That's what a closure is allabout.This 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.=item 5.References are often returned by special subroutines called constructors.Perl objects are just references to a special type of object that happens to knowwhich package it's associated with.  Constructors are just specialsubroutines that know how to create that association.  They do so bystarting with an ordinary reference, and it remains an ordinary referenceeven while it's also being an object.  Constructors are oftennamed new() and called indirectly:    $objref = new Doggie (Tail => 'short', Ears => 'long');But don't have to be:    $objref   = Doggie->new(Tail => 'short', Ears => 'long');    use Term::Cap;    $terminal = Term::Cap->Tgetent( { OSPEED => 9600 });    use Tk;    $main    = MainWindow->new();    $menubar = $main->Frame(-relief              => "raised",                            -borderwidth         => 2)=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.=item 7.A reference can be created by using a special syntax, lovingly known asthe *foo{THING} syntax.  *foo{THING} returns a reference to the THINGslot in *foo (which is the symbol table entry which holds everythingknown as foo).    $scalarref = *foo{SCALAR};    $arrayref  = *ARGV{ARRAY};    $hashref   = *ENV{HASH};    $coderef   = *handler{CODE};    $ioref     = *STDIN{IO};    $globref   = *foo{GLOB};All of these are self-explanatory except for C<*foo{IO}>.  It returnsthe IO handle, used for file handles (L<perlfunc/open>), sockets(L<perlfunc/socket> and L<perlfunc/socketpair>), and directoryhandles (L<perlfunc/opendir>).  For compatibility with previousversions of Perl, C<*foo{FILEHANDLE}> is a synonym for C<*foo{IO}>.C<*foo{THING}> returns undef if that particular THING hasn't been used yet,except in the case of scalars.  C<*foo{SCALAR}> returns a reference to ananonymous scalar if $foo hasn't been used yet.  This might change in afuture release.C<*foo{IO}> is an alternative to the C<*HANDLE> mechanism given inL<perldata/"Typeglobs and Filehandles"> 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.    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\n";    }    $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>;    }=back=head2 Using ReferencesThat'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.=over 4=item 1.Anywhere 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:    $bar = $$scalarref;    push(@$arrayref, $filename);    $$arrayref[0] = "January";    $$hashref{"KEY"} = "VALUE";    &$coderef(1,2,3);    print $globref "output\n";It's important to understand that we are specifically I<not> dereferencingC<$arrayref[0]> or C<$hashref{"KEY"}> there.  The dereference of thescalar variable happens I<before> it does any key lookups.  Anything morecomplicated than a simple scalar variable must use methods 2 or 3 below.However, a "simple scalar" includes an identifier that itself uses method1 recursively.  Therefore, the following prints "howdy".    $refrefref = \\\"howdy";    print $$$$refrefref;=item 2.Anywhere you'd put an identifier (or chain of identifiers) as part of avariable or subroutine name, you can replace the identifier with aBLOCK returning a reference of the correct type.  In other words, theprevious examples could be written like this:    $bar = ${$scalarref};    push(@{$arrayref}, $filename);    ${$arrayref}[0] = "January";    ${$hashref}{"KEY"} = "VALUE";    &{$coderef}(1,2,3);    $globref->print("output\n");  # iff IO::Handle is loadedAdmittedly, it's a little silly to use the curlies in this case, butthe BLOCK can contain any arbitrary expression, in particular,subscripted expressions:    &{ $dispatch{$index} }(1,2,3);	# call correct routineBecause of being able to omit the curlies for the simple case of C<$$x>,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,I<not> case 2:    $$hashref{"KEY"}   = "VALUE";	# CASE 0    ${$hashref}{"KEY"} = "VALUE";	# CASE 1    ${$hashref{"KEY"}} = "VALUE";	# CASE 2    ${$hashref->{"KEY"}} = "VALUE";	# CASE 3Case 2 is also deceptive in that you're accessing a variablecalled %hashref, not dereferencing through $hashref to the hashit's presumably referencing.  That would be case 3.=item 3.Subroutine 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:

⌨️ 快捷键说明

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