Section B.20.  References

Table of Contents

B.20. References

Perl's references are similar to C's pointers, but in operation, they're more like what you have in Pascal or Ada. A reference "points" to a memory location, but because there's no pointer arithmetic or direct memory allocation and deallocation, you can be sure that any reference you have is a valid one. References allow OO programming and complex data structures, among other tricks. See the perlreftut and perlref manpages. The Alpaca covers references in great detail.

B.20.1. Complex Data Structures

References allow us to make complex data structures in Perl. For example, suppose you want a two-dimensional array. You can do that,[*] or you can do something much more interesting, like have an array of hashes, a hash of hashes, or a hash of arrays of hashes.[Section B.20.  References] See the perldsc (data-structures cookbook) and perllol (lists of lists) manpages. The Alpaca covers this thoroughly, including techniques for complex data manipulation, like sorting and summarizing.

[*] Well, not really, but you can fake it so well that you'll hardly remember that there's a difference.

[Section B.20.  References] Actually, you can't make any of these things because these are verbal shorthands for what's happening. What we call "an array of arrays" in Perl is really an array of references to arrays.

B.20.2. Object-Oriented Programming

Yes, Perl has objectsit's buzzword-compatible with all of those other languages. OO programming lets you create your own user-defined datatypes with associated abilities, using inheritance, overriding, and dynamic method lookup.[Section B.20.  References] Unlike some object-oriented languages, Perl doesn't force you to use objects. (Many object-oriented modules can be used without understanding objects.) But if your program is going to be larger than N lines of code, it may be more efficient for the programmer (a tiny bit though slower at runtime) to make it OO. No one knows the precise value of N, but we estimate it's around a few thousand or so. See the perlobj and perlboot manpages for a start, and Damian Conway's excellent Object-Oriented Perl (Manning Press) for more advanced information. The Alpaca book covers objects thoroughly as well.

[Section B.20.  References] OO has its own set of jargon words. Terms used in one OO language will typically not match those in a different OO language.

B.20.3. Anonymous Subroutines and Closures

Odd as it may sound at first, it can be useful to have a subroutine without a name. Such subroutines can be passed as parameters to other subroutines, or they can be accessed via arrays or hashes to make jump tables. Closures are a powerful concept that comes to Perl from the world of Lisp. A closure is (roughly speaking) an anonymous subroutine with its own private data. Again, this is covered in the Alpaca book.

    Table of Contents
    © 2000- NIV