References

12.1 Creating References

use v5.36;
my @arr  = (1, 2, 3);
my %hash = (a => 1, b => 2);
sub hello { say 'hi' }

my $sref = \"a string";        # scalar reference
my $aref = \@arr;              # array reference
my $href = \%hash;             # hash reference
my $cref = \&hello;            # code reference
my $rref = \$aref;             # reference to a reference

# Anonymous data structures
my $anon_array = [1, 2, 3];                  # [] creates an anonymous array ref
my $anon_hash  = { name => 'Ana', age => 30 };   # {} creates an anonymous hash ref
my $anon_sub   = sub ($x) { $x * 2 };         # anonymous subroutine

12.2 Dereferencing

# Element access with the arrow operator
say $aref->[0];                 # 1
say $href->{a};                 # 1
$cref->();                      # call
say $anon_sub->(21);            # 42

# Whole structure
my @copy = @$aref;              # or @{ $aref }
my %h    = %$href;
say scalar @$aref;
for my $k (keys %$href) { ... }

# Postfix dereferencing (5.24+): reads left to right
my @items = $aref->@*;
my %pairs = $href->%*;
my $count = $aref->$#*;         # last index
my @slice = $aref->@[0, 1];
my @vals  = $href->@{qw(a b)};
say "Items: $aref->@*";         # interpolates with the postderef_qq feature (enabled by use v5.24+)

say ref $aref;                  # ARRAY  (ref returns: SCALAR ARRAY HASH CODE REF GLOB Regexp or a class name)
use Scalar::Util qw(reftype blessed looks_like_number);

12.3 Reference Semantics

my $r1 = [1, 2, 3];
my $r2 = $r1;                   # copies the reference, not the data
push @$r2, 4;
say "@$r1";                     # 1 2 3 4 (both point to the same array)

my $shallow = [ @$r1 ];         # shallow copy
use Storable qw(dclone);
my $deep = dclone($complex);    # deep copy

# Weak references avoid circular-reference leaks (Perl uses reference counting)
use Scalar::Util qw(weaken);    # or builtin::weaken (5.40 stable)
my $parent = { name => 'parent' };
my $child  = { name => 'child', parent => $parent };
$parent->{child} = $child;
weaken($child->{parent});       # breaks the cycle

12.4 Code References and Callbacks

sub apply($code, @list) { map { $code->($_) } @list }
my @doubled = apply(sub ($x) { $x * 2 }, 1..5);

my %ops = (
    '+' => sub ($a, $b) { $a + $b },
    '-' => sub ($a, $b) { $a - $b },
);
say $ops{'+'}->(3, 4);