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

#!/usr/bin/perl
package Regular;
use strict;
use warnings;

our $number = 10;

#referencing
our $ref1=\$number;

our $ref2=\$ref1;

$number=90;

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

Hash variable reference

#!/usr/bin/perl
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";
Pdf100
Book40
100
40
Book40
40
Hash variable reference Example

Array Reference

#!/usr/bin/perl
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
Ruby
2 year

Glob appropriate references

#!/usr/bin/perl
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

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


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







© 2021, kalkicode.com, All rights reserved