References — a tutorial#
A reference in Perl is a scalar that points at another value: an array, a hash, a subroutine, another scalar, even another reference. References are the single mechanism that turns Perl’s three container types — scalars, arrays, hashes — into arbitrary nested data structures.
Without references you cannot build a hash of arrays, an array of hashes, a tree, a graph, a record with mixed fields, a callback table, or a closure. With them, you can. This tutorial walks you from the two reference-making operators, through the syntax for getting the underlying value back, up to anonymous constructors, code references, and the weak-reference trick that keeps cyclic structures from leaking.
Who this is for#
You already write working Perl. You use arrays and hashes comfortably, but the moment the problem calls for a hash whose values are arrays — or an array of records, or a callback you can store in a table — the syntax stops being obvious. That gap is what references fill, and what this tutorial closes.
How this tutorial is organised#
Each chapter introduces one concept and stands on its own. Read them in order the first time; jump to the relevant chapter later.
Basics — the
\operator, scalar/array/hash dereference with$$x,@$x,%$x, curly-brace disambiguation, and the->arrow for element access.Arrays of arrays — two-dimensional data, iteration patterns, the arrow-between-subscripts rule that makes
$m[i][j]read as a matrix.Hashes and mixes — hashes of arrays, arrays of hashes, and the common record-table shape.
Anonymous references —
[...]and{...}as inline constructors, when to choose them over named variables.Subroutine references —
\&name, anonymoussub { ... }, calling with->(...), and how closures capture lexicals.Weak references —
Scalar::Util::weakenand why cyclic structures need it.