PERL / CHAPTER 05

References and nested structures

Advanced

Represent nested records while making shared data explicit.

By the end of this chapter

  • Create array and hash references
  • Dereference with arrow syntax
  • Distinguish copying a reference from copying its target

The idea

Enter with arrays, hashes, and subroutines understood. A reference is a scalar value identifying another value or structure. Square brackets construct an anonymous array reference, and braces can construct an anonymous hash reference. References allow nested collections because each outer element remains a scalar. Arrow notation accesses an element through a reference, making the level of indirection visible.

Assigning a reference to another variable does not clone its target. Both references can observe later changes to the same array or hash. To copy a flat array’s elements, construct a new array from the dereferenced source. If those elements are themselves references, that operation still shares the nested targets. State whether a helper borrows, mutates, or copies a structure instead of promising independence without defining its depth.

Perl example
use strict; use warnings;
my $first=[2,4];
my $alias=$first;
$alias->[1]=9;
print join(",",@$first),"\n";
Result
2,9

Both scalar variables contain references to the same array. Updating through alias changes the data observed through first.

Try it yourself

Build a hash reference containing a name and an array reference of scores, then access its second score.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What does my $b=$a do when $a is an array reference?