Chapter 8. References
For both practical and philosophical reasons, Perl has always been biased in favor of flat, linear data structures. And for many problems, this is just what you want.
Suppose you wanted to build a simple table (two-dimensional array) showing vital statistics--age, eye color, and weight--for a group of people. You could do this by first creating an array for each individual:
@john = (47, "brown", 186); @mary = (23, "hazel", 128); @bill = (35, "blue", 157);
You could then construct a single, additional array consisting of the names of the other arrays:
@vitals = ('john', 'mary', 'bill');
To change John's eyes to "red" after a night on the town,
we want a way to change the contents of the @john
array given only the simple string "john
". This is
the basic problem of indirection, which various
languages solve in various ways. In C, the most common form of
indirection is the pointer, which lets one variable hold the memory
address of another variable. In Perl, the most common form of
indirection is the reference.
What Is a Reference?
In our example, $vitals[0]
has the
value "john
". That is, it contains a string that
happens to be the name of another (global) variable. We say that the
first variable refers to the second, and this
sort of reference is called a symbolic reference,
since Perl has to look up @john
in a symbol table to find it. (You might think of symbolic references as analogous to symbolic links in the filesystem.) We'll talk about symbolic references later ...
Get Programming Perl, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.