Search⌘ K

Types of References I

Explore Perl references including scalar, array, and hash references, and understand how to dereference them correctly. Learn to create anonymous data structures, use references for memory efficiency, and manipulate complex nested data using packages and references.

Scalar references

The reference operator is the backslash \. In scalar context, it creates a single reference that refers to another value. In list context, it creates a list of references. To take a reference to $name, we can do this:

my $name = 'Larry';
my $name_ref = \$name;

We must dereference a reference to evaluate the value to which it refers. Dereferencing requires us to add an extra sigil for each level of dereferencing:

Perl
sub reverse_in_place {
my $name_ref = shift;
$$name_ref = reverse $$name_ref;
}
my $name = 'Blabby';
reverse_in_place( \$name );
say $name;

The double scalar sigil $$ dereferences a scalar reference.

Parameters in @_ behave as aliasesThat is, if we access @_ directly, we can modify the arguments passed to the function. to caller variables so that we can modify them in place:

Perl
sub reverse_value_in_place {
$_[0] = reverse $_[0];
}
my $name = 'allizocohC';
reverse_value_in_place($name);
say $name;

We usually don’t want to modify values this way—callers rarely expect it, for example. Assigning parameters to lexicals within our functions makes copies of the values in @_ and avoids this aliasing behavior.

Note: Modifying a value in place or returning a reference to a scalar can save memory. Because Perl ...