References and Data Structures

Complex Data Structures - Introduction

We have already learned the Perl syntax required for creating and using linear data structures such as arrays and hashes.

Perl does not provide, however, any special syntax for more complex data structures, such as two-dimensional arrays, hashes of hashes, records etc.

Instead, to use such structures we have to employ references. Fortunately, once you understand the principles of referencing and dereferencing, creating complex data structures is straightforward.

Perl's way of implementing complex data structures using references enables us extreme flexibility in the structures we build.

The principle is simple:

This can go deeper and deeper, to create as many levels of nested structures as we wish. The structures can be homogeneous, for example: every element of an array points to (is a reference to) another array, or: every element of an array points to another hash. Alternatively, the structure can be non-homogeneous, for example: the first element of an array points to another array, the second element of the array points to a hash, and the third element of the array contains a simple scalar value.

Data structures in our program can be built during the course of the program, they can grow, elements of various types (simple, or references to other structures) can be added to them, or deleted from them. This mechanism, again, makes our data structures very flexible and dynamic.

When we build a complex data structure, it is often useful to create a reference to the entire structure. This reference can then be easily delivered to/from subroutines. The data contained in the structure is actually stored in a certain set of memory cells in our computer. In fact, what we deliver between the main program and the various subroutines are pointers to the physical memory cells. Thus, different subroutines can manipulate the same data that's inside the structure. The data itself never goes out of scope. Only the scalar containing the reference to the entire structure might go out of scope, so we have to take care to deliver it properly to the subroutines.

Table of Contents.
Previous | Next.