References in Perl

Walden Systems Geeks Corner References in Perl programming howto tutorial Rutherford NJ New Jersey NYC North Bergen County
Perl 5 is a highly capable, feature-rich programming language with over 30 years of development. Perl 5 runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large scale development projects.

A reference is a scalar variable that refers to another object which can be a scalar, an array or a hash. A reference holds a memory address of the object that it refers to. When a reference is dereferenced, we can manipulate data of the object that the reference refers to. The act of retrieving data through a reference is called dereferencing. References are useful since a reference is a scalar variable, we can put a reference inside arrays and hashes to create complex data structures.

Referencing syntax

There are two important rules to remember when working with references. In order to create a reference to a variable or subroutine, we use the backslash operator () in front of the variable or subroutine name. We can't create a reference on an I/O handle using the backslash operator but we can create a reference to an anonymous array using the square brackets.

$scalarref = $foo;
$arrayref  = @ARGV;
$hashref   = \%ENV;
$coderef   = &handler;
$globref   = *foo;
$ioarrayref = [1, 2, ['a', 'b', 'c']];


Dereferencing syntax

Dereferencing returns the value from a reference point to the location. To dereference a reference to a scalar, we use the $ as prefix of the reference variable. To dereference a reference to an array, we use @ as prefix of the reference variable. To dereference a reference to a hash, we use % as prefix of the reference variable. as prefix of the reference variable. To deference a reference to a subroutine, we use the & as prefix of the reference variable.

print "$$scalrref";
print "@$arrayref";
print "%$hashref";
&$funcref() ;

Circular references

Be careful not to create circular references. A circular reference occurs when two references contain a reference to each other. we have to be careful while creating references otherwise a circular reference can lead to memory leaks. Memory leaks occur because when Perl data structures go out of scope, the reference counting garbage collector won't clean it up.