📄 perlref.pod
字号:
=head1 NAME
perlref - Perl references and nested data structures
=head1 DESCRIPTION
Before release 5 of Perl it was difficult to represent complex data
structures, because all references had to be symbolic--and even then
it 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 contain
scalars, 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 goes
to zero. (Note: the reference counts for values in self-referential or
cyclic data structures may not go to zero without a little help; see
L<perlobj/"Two-Phased Garbage Collection"> for a detailed explanation.)
If that thing happens to be an object, the object is destructed. See
L<perlobj> for more about objects. (In a sense, everything in Perl is an
object, but we usually reserve the word for references to objects that
have been officially "blessed" into a class package.)
Symbolic references are names of variables or other objects, just as a
symbolic link in a Unix filesystem contains merely the name of a file.
The C<*glob> notation is a kind of symbolic reference. (Symbolic
references are sometimes called "soft references", but please don't call
them that; references are confusing enough without useless synonyms.)
In contrast, hard references are more like hard links in a Unix file
system: They are used to access an underlying object without concern for
what its (other) name is. When the word "reference" is used without an
adjective, as in the following paragraph, it is usually talking about a
hard reference.
References are easy to use in Perl. There is just one overriding
principle: Perl does no implicit referencing or dereferencing. When a
scalar is holding a reference, it always behaves as a simple scalar. It
doesn't magically start being an array or hash or subroutine; you have to
tell it explicitly to do so, by dereferencing it.
=head2 Making References
References 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.) Note
that this typically creates I<ANOTHER> reference to a variable, because
there's already a reference to the variable in the symbol table. But
the symbol table reference might go away, and you'll still have the
reference 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 (filehandle
or dirhandle) using the backslash operator. The most you can get is a
reference 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 square
brackets:
$arrayref = [1, 2, ['a', 'b', 'c']];
Here we've created a reference to an anonymous array of three elements
whose final element is itself a reference to another anonymous array of three
elements. (The multidimensional syntax described later can be used to
access this. For example, after the above, C<$arrayref-E<gt>[2][1]> would have
the value "b".)
Note that taking a reference to an enumerated list is not the same
as using square brackets--instead it's the same as creating
a 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 contents
of C<@foo>, not a reference to C<@foo> itself. Likewise for C<%foo>.
=item 3.
A reference to an anonymous hash can be created using curly
brackets:
$hashref = {
'Adam' => 'Eve',
'Clyde' => 'Bonnie',
};
Anonymous hash and array composers like these can be intermixed freely to
produce as complicated a structure as you want. The multidimensional
syntax described below works for these too. The values above are
literals, but variables and expressions would work just as well, because
assignment operators in Perl (even within local() or my()) are executable
statements, not compile-time declarations.
Because curly brackets (braces) are used for several other things
including BLOCKs, you may occasionally have to disambiguate braces at the
beginning of a statement by putting a C<+> or a C<return> in front so
that Perl realizes the opening brace isn't starting a BLOCK. The economy and
mnemonic value of using curlies is deemed worth this occasional extra
hassle.
For example, if you wanted a function to make a new hash and return a
reference to it, you have these options:
sub hashem { { @_ } } # silently wrong
sub hashem { +{ @_ } } # ok
sub hashem { return { @_ } } # ok
On 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 @_ } } # ok
Note how the leading C<+{> and C<{;> always serve to disambiguate
the expression to mean either the HASH reference, or the BLOCK.
=item 4.
A reference to an anonymous subroutine can be created by using
C<sub> without a subname:
$coderef = sub { print "Boink!\n" };
Note the presence of the semicolon. Except for the fact that the code
inside isn't executed immediately, a C<sub {}> is not so much a
declaration as it is an operator, like C<do{}> or C<eval{}>. (However, no
matter how many times you execute that particular line (unless you're in an
C<eval("...")>), C<$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 visible lexically within the current scope. Closure
is a notion out of the Lisp world that says if you define an anonymous
function in a particular lexical context, it pretends to run in that
context even when it's called outside of the context.
In human terms, it's a funny way of passing arguments to a subroutine when
you define it as well as when you call it. It's useful for setting up
little bits of code to run later, such as callbacks. You can even
do object-oriented stuff with it, though Perl already provides a different
mechanism to do that--see L<perlobj>.
You can also think of closure as a way to write a subroutine template without
using eval. (In fact, in version 5.000, eval was the I<only> way to get
closures. You may wish to use "require 5.001" if you use closures.)
Here's a small example of how closures works:
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 passed into
newprint() I<despite> the fact that the "my $x" has seemingly gone out of
scope by the time the anonymous subroutine runs. That's what closure
is all about.
This applies only to lexical variables, by the way. Dynamic variables
continue to work as they have always worked. Closure is not something
that 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 kind of object that happens to know
which package it's associated with. Constructors are just special
subroutines that know how to create that association. They do so by
starting with an ordinary reference, and it remains an ordinary reference
even while it's also being an object. Constructors are often
named 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 you
dereference them in a context that assumes they exist. Because we haven't
talked 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 as
the *foo{THING} syntax. *foo{THING} returns a reference to the THING
slot in *foo (which is the symbol table entry which holds everything
known 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 *foo{IO}. It returns the
IO handle, used for file handles (L<perlfunc/open>), sockets
(L<perlfunc/socket> and L<perlfunc/socketpair>), and directory handles
(L<perlfunc/opendir>). For compatibility with previous versions of
Perl, *foo{FILEHANDLE} is a synonym for *foo{IO}.
*foo{THING} returns undef if that particular THING hasn't been used yet,
except in the case of scalars. *foo{SCALAR} returns a reference to an
anonymous scalar if $foo hasn't been used yet. This might change in a
future release.
*foo{IO} is an alternative to the \*HANDLE mechanism given in
L<perldata/"Typeglobs and Filehandles"> for passing filehandles
into 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 no risk of clobbering more than you want
to with a typeglob assignment, although if you assign to a scalar instead
of a typeglob, you're ok.
splutter(*STDOUT);
splutter(*STDOUT{IO});
sub splutter {
my $fh = shift;
print $fh "her um well a hmmm\n";
}
$rec = get_rec(*STDIN);
$rec = get_rec(*STDIN{IO});
sub get_rec {
my $fh = shift;
return scalar <$fh>;
}
=back
=head2 Using References
That's it for creating references. By now you're probably dying to
know how to use references to get back to your long-lost data. There
are several basic methods.
=over 4
=item 1.
Anywhere you'd put an identifier (or chain of identifiers) as part
of a variable or subroutine name, you can replace the identifier with
a 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> dereferencing
C<$arrayref[0]> or C<$hashref{"KEY"}> there. The dereference of the
scalar variable happens I<BEFORE> it does any key lookups. Anything more
complicated than a simple scalar variable must use methods 2 or 3 below.
However, a "simple scalar" includes an identifier that itself uses method
1 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 a
variable or subroutine name, you can replace the identifier with a
BLOCK returning a reference of the correct type. In other words, the
previous 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 loaded
Admittedly, it's a little silly to use the curlies in this case, but
the BLOCK can contain any arbitrary expression, in particular,
subscripted expressions:
&{ $dispatch{$index} }(1,2,3); # call correct routine
Because of being able to omit the curlies for the simple case of C<$$x>,
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -