BudiBadu Logo
Samplebadu

Perl by Example: References

Perl 5

Building complex data structures with this code example demonstrating reference creation using backslash operator, anonymous array and hash references with brackets and braces, arrow operator for dereferencing, and nested structure navigation.

Code

#!/usr/bin/perl
use strict;
use warnings;

# Create a reference to an array using backslash
my @array = (1, 2, 3);
my $array_ref = \@array;

# Create an anonymous array reference using square brackets
my $anon_array_ref = [4, 5, 6];

# Create an anonymous hash reference using curly braces
my $user = {
    name => "Alice",
    role => "Admin"
};

# Dereferencing
print "First element: $array_ref->[0]\n";
print "User name: $user->{name}\n";

# Nested structures (Array of Hashes)
my $people = [
    { name => "Bob", age => 25 },
    { name => "Charlie", age => 30 }
];

print "Bob's age: $people->[0]->{age}\n";

Explanation

References in Perl are scalar variables that point to other data structures including scalars, arrays, hashes, or subroutines. References enable the creation of complex data structures like arrays of arrays, hashes of hashes, or any combination thereof. The backslash operator \ creates a reference to an existing variable, returning a scalar that points to the original data structure.

Anonymous data structures are created without named variables using square brackets [] for anonymous array references and curly braces {} for anonymous hash references. This syntax resembles JSON and is commonly used for configuration data, object-like structures, and nested data. Anonymous structures are automatically reference-counted and garbage-collected when no longer referenced.

The arrow operator -> dereferences references to access their contents. For array references, $arrayref->[index] accesses elements, while for hash references, $hashref->{key} accesses values. The arrow operator chains cleanly for nested structures like $ref->[0]->{key}. Alternative dereferencing syntax includes @{$arrayref} for entire arrays and %{$hashref} for entire hashes, though the arrow notation is more common for element access.

Code Breakdown

7
\@array backslash operator creates reference to existing array.
10
[4, 5, 6] square brackets create anonymous array reference.
13
{...} curly braces create anonymous hash reference.
28
-> arrow operator dereferences, chains for nested structure navigation.