Perl Referance

What is Perl reference?
A reference is a scalar variable that “points”  or refers to another object which can be a scalar, an array, a hash, etc.  
A reference holds a memory address of the object that it points to.
When a reference is dereferenced, you can manipulate data of the object that the reference refers to. 

Why do you need Perl references?
Reference is a scalar variable, so you can put a reference inside arrays and hashes. 
You can create complex data structures such as arrays of arrays, arrays of hashes, hashes of hashes, etc.
With references, you can create not only two-dimensional but also multidimensional data structures.

Syntax of references
To create a reference to a variable or subroutine, you use the unary backslash operator (\) in front of the variable or subroutine name. 

For example, to create a reference $foo that refers to scalar $bar, you do it as follows:

$foo = \$bar;

Dereferencing returns the value from a reference point to the location.

To dereference a reference, you prefix $ to a scalar, @ to an array, % to a hash, and & to a subroutine. 

For example, to dereference a scalar reference $foo, you use:

$$foo;

Example:
1) Reference to Scalar Variable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#!/usr/bin/perl
use warnings;
use strict;

#A scalar variable 
my $x = 10;

#Creating a referance variable to Scalar variable $x
my $xref = \$x;

print("$$xref \n");  # 20
 
# change $x via $xr
$$xref = $$xref * 2;
 
print("$x\n"); # 20
print("$$xref \n");  # 20
print("$xref\n"); # SCALAR(0x47d0f54)
Output:
10
20
20
SCALAR(0x47d0f54)

2) Reference to Array and Hash.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/perl

#1) Arrays
my @array = ("Tom","Jack","Orpaz","Jerry");

#A referance variable to array
my $array_ref = \@array;

# Print values available at the location stored in $array_ref.
print "Values: ",  @$array_ref, "\n";

#2) Hash
%var = ('key1' => 10, 'key2' => 20);

# Now $r has reference to %var hash.
$r = \%var;

# Print values available at the location stored in $r.
print "Value of %var is : ", %$r, "\n";
Output:
Values: TomJackOrpazJerry
Value of %var is : key220key110

<-- Previous || Next -->

1 comment: