--- name: references tutorial --- ```{index} single: reference single: nested data structure ``` # 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. ```{toctree} :maxdepth: 1 basics arrays-of-arrays hashes-and-mixes anonymous-refs subroutine-refs weak-refs ``` - **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`, anonymous `sub { ... }`, calling with `->(...)`, and how closures capture lexicals. - **Weak references** - `Scalar::Util::weaken` and why cyclic structures need it. ## Related reference pages - [`ref`](../../p5/core/perlfunc/ref) - ask a value what kind of reference it is. - [`defined`](../../p5/core/perlfunc/defined) - the standard way to check "does this reference exist yet?" after autovivification. - [`bless`](../../p5/core/perlfunc/bless) - the step that turns a plain reference into an object. - [References (data-types reference)](../../p5/core/perldata/references) - the terse one-page reference that complements this tutorial.