In Perl, simple data structures are scalars, arrays, and hashes that we access directly by name. References are scalars that contain the addresses of other data structures. They are necessary for creating nested (multidimensional) arrays, nested hashes, and complex objects.
Example of using references:
my %hash = ( foo => 1, bar => 2 ); my $ref = \%hash; print $ref->{foo}; # 1 # Array of references to hashes my @array = ( { name => "Tom" }, { name => "Jerry" } ); print $array[1]{name}; # Jerry
If references are not used, it is impossible to create, for example, a multidimensional array:
# Multidimensional array via references my $matrix = [ [1,2,3], [4,5,6] ]; print $matrix->[1][2]; # 6
This allows for building complex data structures, passing them compactly between functions, and implementing OOP patterns.
Can you access an element of a nested array (or hash) without using references? If yes — how, and when will this not work?
It is often answered that you cannot, however, Perl sometimes "automatically" converts structures. But without references, nested structures will not work when created on the fly or when passed as arguments.
Example of incorrect and correct access:
# This won’t work like this: my @arr = ( [1,2],[3,4] ); print $arr[0][1]; # 2 # But if declared not as a reference but just an array, then: my @matrix = ( [1,2], [3,4] ); print $matrix[1][0]; # 3
Story
In a large project, a reference to an array was attempted to be passed without the \ operator, which caused the internal structure to "unroll" as an array of scalars, leading to a complete disruption of logic.
Story
A developer mixed accessing by reference and without a reference in code, resulting in some data being lost during nested foreach loops while working with an array of references.
Story
When working with a configuration nested via a hash of references, they forgot to dereference the reference and accessed it as a hash, which caused a "Can't use string ("HASH(0x1234)") as a HASH" runtime error in production.