Dereferencing in Perl

PERLServer Side ProgrammingProgramming Scripts

Dereferencing in Perl returns the value from a reference point to the location. To dereference a reference simply use $, @ or % as a prefix of the reference variable depending on whether the reference is pointing to a scalar, array, or hash. Following is the example to explain the concept −

Example

 Live Demo

#!/usr/bin/perl
$var = 10;

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

# Print value available at the location stored in $r.
print "Value of $var is : ", $$r, "\n";
@var = (1, 2, 3);

# Now $r has reference to @var array.
$r = \@var;

# Print values available at the location stored in $r.
print "Value of @var is : ", @$r, "\n";
%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

When the above program is executed, it produces the following result −

Value of 10 is : 10
Value of 1 2 3 is : 123
Value of %var is : key220key110

If you are not sure about a variable type, then it's easy to know its type using ref, which returns one of the following strings if its argument is a reference. Otherwise, it returns false −

SCALAR
ARRAY
HASH
CODE
GLOB
REF

Example

Let's try the following example −

 Live Demo

#!/usr/bin/perl
$var = 10;
$r = \$var;
print "Reference type in r : ", ref($r), "\n";
@var = (1, 2, 3);
$r = \@var;
print "Reference type in r : ", ref($r), "\n";
%var = ('key1' => 10, 'key2' => 20);
$r = \%var;
print "Reference type in r : ", ref($r), "\n";

Output

When the above program is executed, it produces the following result −

Reference type in r : SCALAR
Reference type in r : ARRAY
Reference type in r : HASH
raja
Published on 29-Nov-2019 11:46:39
Advertisements