What Is a Reference?

A reference is a form of data in Perl that indirectly points to some other bit of data. The reference itself is a scalar, like a number or string—it can be assigned to a scalar variable, printed, added to, tested to see if it's true or false, stored in a list, or passed to a subroutine, just as numbers and strings can. In addition to its scalar-like behavior, however, the reference also refers, or points to, the location of some other bit of data. To find out what the reference points to, you dereference the reference—fancy terminology for essentially following the pointer to the thing it points to.

Note

If you actually want more fancy terminology in your life, the thing the reference points to is called the referent. You dereference the reference to get to the referent. Me, I prefer regular words like “the thing it points to.”


References in Perl are similar to pointers or references in other languages, and have the same advantages. But, if you're not used to other languages, you might wonder, “What's the point? Why would you want to deal with a reference when you could deal with the data itself?” The answer is that by indirectly referring to data, you can do more advanced things with that data—for example, pass large amounts of data by reference into and out of subroutines, or create multidimensional arrays. References also allow more advanced uses of data, including creating object-oriented structures in Perl. We'll look at a number of these uses as the lesson progresses.

There's one other technical point to make before we move on to actual code. What I'm referring to in this chapter as references are known in technical Perl circles as hard references. Perl also has another form of reference called a symbolic reference. Although there are perfectly good reasons for using symbolic references, hard references are more useful in general, so for the bulk of this chapter we'll stick to those. I'll talk more about symbolic references in “Going Deeper” at the end of this lesson.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset