Nested Data Structures
Explore how Perl references enable the creation and manipulation of nested data structures such as arrays and hashes within arrays or hashes. Understand the role of autovivification, the use of dereferencing syntax, and strategies for managing code clarity and safety when working with complex data models.
We'll cover the following...
Storing an array in an array
Perl’s aggregate data types—arrays and hashes—store scalars indexed by integer or string keys. Note the word scalar. If we try to store an array in an array, Perl’s automatic list flattening will make everything into a single array:
Use references
Perl’s solution to this is references, which are special scalars that can refer to other variables. Nested data structures in Perl, such as an array of arrays or a hash of hashes, are possible through the use of references. Unfortunately, the reference syntax isn’t the most visually appealing.
We can use the reference operator \ to produce a reference to a named variable:
Alternatively, we can use the anonymous reference declaration syntax to avoid the use of named variables:
Note: Perl allows an optional trailing ...