Skip to main content

Perl Reference

Reference is an most useful features in perl Programming, That is similar to pointers in C and C++ programming. Using of referencing there is possible to get and manipulate values of variable. Here include examples of scalar,array and hash variable referencing.

What is referencing? In simple terms reference is a way to operate a values using of memory address. In perl programming Scalar variable are capable to store the address of an object element. And using of this address that can use or modified their values. This process is called deferencing.

Why use referencing? There are two main reason. Referencing are provide reusability of a variable memory which is already create to other variable.

And second advantage is by using of referencing there are possible to implement complex data structure in array or hash elements.

Scalar Variable Reference

package Regular;
use strict;
use warnings;

our $number = 10;

our $ref1=\$number;

our $ref2=\$ref1;


print $$ref1,"\n"; #90
print $$$ref2,"\n"; #90
Scalar variable reference

Hash variable reference

package Regular;
use strict;
use warnings;

our %data=("Image"=>50,"Pdf"=>100,"Book"=>40);

our $ref1 = \%data;

our %ref2 =("Document"=>\%data) ;

#get key pair
print %$ref1{'Pdf'},"\n";
print %$ref1{'Book'},"\n";

#get values
print $$ref1{'Pdf'},"\n";
print $$ref1{'Book'},"\n";

print %{$ref2{'Document'}}{"Book"},"\n";
print ${$ref2{'Document'}}{"Book"},"\n";
Hash variable reference Example

Array Reference

package Regular;
use strict;
use warnings;

our $name = "Ruby";
our $age = 27; 

our %experience = (it => "2 year",
            management => "5 year");

our @record = (\$name,\$age,\%experience);

our $info =\@record;

print ${@{$info}[0]},"\n"; #Ruby

print ${@{$info}[2]}{'it'},"\n"; #2 year
Array reference example
2 year

Glob appropriate references

package Regular;

*vars = \"Code";
*vars = [ 10, 20, 30 ,40 ];
*vars = {one=> 1, green => "green", blue => "blue" };

print $vars,"\n";        # Code
print @vars[1],"\n";     # 20
print $vars["one"],"\n";  #1

print $Regular::vars,"\n";        # Code
print @Regular::vars[1],"\n";     # 20
print $Regular::vars["one"],"\n";  #1
glob appropriate references


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment