=head1 NAME
+X<reference> X<pointer> X<data structure> X<structure> X<struct>
perlref - Perl references and nested data structures
The C<*glob> notation is something of a symbolic reference. (Symbolic
references are sometimes called "soft references", but please don't call
them that; references are confusing enough without useless synonyms.)
+X<reference, symbolic> X<reference, soft>
+X<symbolic reference> X<soft reference>
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.
+X<reference, hard> X<hard reference>
References are easy to use in Perl. There is just one overriding
principle: Perl does no implicit referencing or dereferencing. When a
tell it explicitly to do so, by dereferencing it.
=head2 Making References
+X<reference, creation> X<referencing>
References can be created in several ways.
=over 4
=item 1.
+X<\> X<backslash>
By using the backslash operator on a variable, subroutine, or value.
(This works much like the & (address-of) operator in C.)
you can still use type globs and globrefs as though they were IO handles.
=item 2.
+X<array, anonymous> X<[> X<[]> X<square bracket>
+X<bracket, square> X<arrayref> X<array reference> X<reference, array>
A reference to an anonymous array can be created using square
brackets:
strings rather than full-fledged scalars).
=item 3.
+X<hash, anonymous> X<{> X<{}> X<curly bracket>
+X<bracket, curly> X<brace> X<hashref> X<hash reference> X<reference, hash>
A reference to an anonymous hash can be created using curly
brackets:
the expression to mean either the HASH reference, or the BLOCK.
=item 4.
+X<subroutine, anonymous> X<subroutine, reference> X<reference, subroutine>
+X<scope, lexical> X<closure> X<lexical> X<lexical scope>
A reference to an anonymous subroutine can be created by using
C<sub> without a subname:
that most Perl programmers need trouble themselves about to begin with.
=item 5.
+X<constructor> X<new>
References are often returned by special subroutines called constructors.
Perl objects are just references to a special type of object that happens to know
-borderwidth => 2)
=item 6.
+X<autovivification>
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.
+X<*foo{THING}> X<*>
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
$coderef = *handler{CODE};
$ioref = *STDIN{IO};
$globref = *foo{GLOB};
+ $formatref = *foo{FORMAT};
All of these are self-explanatory except for C<*foo{IO}>. It returns
the IO handle, used for file handles (L<perlfunc/open>), sockets
=back
=head2 Using References
+X<reference, use> X<dereferencing> X<dereference>
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
print $$$$refrefref;
=item 2.
+X<${}> X<@{}> X<%{}>
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
it's presumably referencing. That would be case 3.
=item 3.
+X<autovivification> X<< -> >> X<arrow>
Subroutine calls and lookups of individual array elements arise often
enough that it gets cumbersome to use method 2. As a form of
to grow its arrays on demand. Perl does.
=item 4.
+X<encapsulation>
If a reference happens to be a reference to an object, then there are
probably methods to access the things referred to, and you should probably
integer representing its storage location in memory. The only
useful thing to be done with this is to compare two references
numerically to see whether they refer to the same location.
+X<reference, numeric context>
if ($ref1 == $ref2) { # cheap numeric compare of references
print "refs 1 and 2 refer to the same thing\n";
as the numeric address expressed in hex. The ref() operator returns
just the type of thing the reference is pointing to, without the
address. See L<perlfunc/ref> for details and examples of its use.
+X<reference, string context>
The bless() operator may be used to associate the object a reference
points to with a package functioning as an object class. See L<perlobj>.
print "That yields @{[$n + 5]} widgets\n";
=head2 Symbolic references
+X<reference, symbolic> X<reference, soft>
+X<symbolic reference> X<soft reference>
We said that references spring into existence as necessary if they are
undefined, but we didn't say what happens if a value used as a
string is effectively quoted.
=head2 Pseudo-hashes: Using an array as a hash
+X<pseudo-hash> X<pseudo hash> X<pseudohash>
-B<WARNING>: This section describes an experimental feature. Details may
-change without notice in future versions.
-
-B<NOTE>: The current user-visible implementation of pseudo-hashes
-(the weird use of the first array element) is deprecated starting from
-Perl 5.8.0 and will be removed in Perl 5.10.0, and the feature will be
-implemented differently. Not only is the current interface rather ugly,
-but the current implementation slows down normal array and hash use quite
-noticeably. The 'fields' pragma interface will remain available.
-
-Beginning with release 5.005 of Perl, you may use an array reference
-in some contexts that would normally require a hash reference. This
-allows you to access array elements using symbolic names, as if they
-were fields in a structure.
-
-For this to work, the array must contain extra information. The first
-element of the array has to be a hash reference that maps field names
-to array indices. Here is an example:
-
- $struct = [{foo => 1, bar => 2}, "FOO", "BAR"];
-
- $struct->{foo}; # same as $struct->[1], i.e. "FOO"
- $struct->{bar}; # same as $struct->[2], i.e. "BAR"
-
- keys %$struct; # will return ("foo", "bar") in some order
- values %$struct; # will return ("FOO", "BAR") in same some order
-
- while (my($k,$v) = each %$struct) {
- print "$k => $v\n";
- }
-
-Perl will raise an exception if you try to access nonexistent fields.
-To avoid inconsistencies, always use the fields::phash() function
-provided by the C<fields> pragma.
-
- use fields;
- $pseudohash = fields::phash(foo => "FOO", bar => "BAR");
-
-For better performance, Perl can also do the translation from field
-names to array indices at compile time for typed object references.
-See L<fields>.
-
-There are two ways to check for the existence of a key in a
-pseudo-hash. The first is to use exists(). This checks to see if the
-given field has ever been set. It acts this way to match the behavior
-of a regular hash. For instance:
-
- use fields;
- $phash = fields::phash([qw(foo bar pants)], ['FOO']);
- $phash->{pants} = undef;
-
- print exists $phash->{foo}; # true, 'foo' was set in the declaration
- print exists $phash->{bar}; # false, 'bar' has not been used.
- print exists $phash->{pants}; # true, your 'pants' have been touched
-
-The second is to use exists() on the hash reference sitting in the
-first array element. This checks to see if the given key is a valid
-field in the pseudo-hash.
-
- print exists $phash->[0]{bar}; # true, 'bar' is a valid field
- print exists $phash->[0]{shoes};# false, 'shoes' can't be used
-
-delete() on a pseudo-hash element only deletes the value corresponding
-to the key, not the key itself. To delete the key, you'll have to
-explicitly delete it from the first hash element.
-
- print delete $phash->{foo}; # prints $phash->[1], "FOO"
- print exists $phash->{foo}; # false
- print exists $phash->[0]{foo}; # true, key still exists
- print delete $phash->[0]{foo}; # now key is gone
- print $phash->{foo}; # runtime exception
+Pseudo-hashes have been removed from Perl. The 'fields' pragma
+remains available.
=head2 Function Templates
+X<scope, lexical> X<closure> X<lexical> X<lexical scope>
+X<subroutine, nested> X<sub, nested> X<subroutine, local> X<sub, local>
-As explained above, a closure is an anonymous function with access to the
-lexical variables visible when that function was compiled. It retains
-access to those variables even though it doesn't get run until later,
-such as in a signal handler or a Tk callback.
+As explained above, an anonymous function with access to the lexical
+variables visible when that function was compiled, creates a closure. It
+retains access to those variables even though it doesn't get run until
+later, such as in a signal handler or a Tk callback.
Using a closure as a function template allows us to generate many functions
that act similarly. Suppose you wanted functions named after the colors
Access to lexicals that change over type--like those in the C<for> loop
above--only works with closures, not general subroutines. In the general
case, then, named subroutines do not nest properly, although anonymous
-ones do. If you are accustomed to using nested subroutines in other
-programming languages with their own private variables, you'll have to
-work at it a bit in Perl. The intuitive coding of this type of thing
-incurs mysterious warnings about ``will not stay shared''. For example,
-this won't work:
+ones do. Thus is because named subroutines are created (and capture any
+outer lexicals) only once at compile time, whereas anonymous subroutines
+get to capture each time you execute the 'sub' operator. If you are
+accustomed to using nested subroutines in other programming languages with
+their own private variables, you'll have to work at it a bit in Perl. The
+intuitive coding of this type of thing incurs mysterious warnings about
+"will not stay shared". For example, this won't work:
sub outer {
my $x = $_[0] + 35;
sub inner { return $x * 19 } # WRONG
return $x + inner();
- }
+ }
A work-around is the following:
my $x = $_[0] + 35;
local *inner = sub { return $x * 19 };
return $x + inner();
- }
+ }
Now inner() can only be called from within outer(), because of the
temporary assignments of the closure (anonymous subroutine). But when
function, something not normally supported in Perl.
=head1 WARNING
+X<reference, string context> X<reference, use as hash key>
You may not (usefully) use a reference as the key to a hash. It will be
converted into a string: