What are references in Perl?

A reference is a scalara variable that stores a single unit of data at a time variable in Perl that points to another variable and holds its memory address.

The variable that reference points to can be:

  • a numeric type
  • an array
  • a hash
  • a string type
  • etc.

Note: ; - semicolons are mandatory while declaring, initializing, and executing statements in Perl.

Syntax

We can declare a reference by adding backslash (\) before a variable name.

$var1 = 69;

$ref_var1 = \$var1;
Reference memory storage in Perl

Code

Example 01

The following code snippet shows how we can declare and store variable references to another scalar type.

# Scalar string value reference
$number = 1234;
$integer_reference = \$number;
print "Scalar Numeric reference: $integer_reference";
# Scalar
$string = "Hello World!";
$string_reference = \$string;
print "\nScalar String reference: $string_reference";
# Array Reference
@array = ('0', '1', '2', '3');
$array_reference = \@array;
print "\nScalar Array reference: $array_reference";
# Hash Reference
%hash = ('61'=>'a', '62'=>'b', '63'=>'c', '64'=>'d');
$hash_reference = \%hash;
print "\nScalar Hash reference: $hash_reference";

Dereferencing in Perl

For the above example, we have learned how to reference a variable using a backslash (\) . To access the content at that memory address, we will dereference the scalar variable.

Dereferencing is a way of accessing the stored memory of a variable using the same symbol of their datatype, e.g., @ for arrays, for variables, and % for hashes.

Dereference memory storage in Perl

Example 02

Take a look at the following example that shows how to dereference a variable.

# Scalar string value reference
$number = 1234;
$integer_reference = \$number;
# print "Scalar Numeric reference: $integer_reference";
print $$integer_reference;
# Scalar
$string = "Hello World!";
$string_reference = \$string;
# print "\nScalar String reference: $string_reference";
print "\n";
print $$string_reference;
# Array Reference
@array = ('0', '1', '2', '3');
$array_reference = \@array;
# print "\nScalar Array reference: $array_reference";
print "\n";
print @$array_reference;
# Hash Reference
%hash = ('61'=>'a ', '62'=>'b ', '63'=>'c ', '64'=>'d ');
$hash_reference = \%hash;
# print "\nScalar Hash reference: $hash_reference";
print "\n";
print %$hash_reference;

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved