Perl – References

References in Perl is just imitation of Pointers in C

In C,   *p = &var;

In Perl, $p = \$var;

These references can be applied to all kinds of variables, function, hashes and arrays. Just add \ before the variable/function name and assign to a reference variable which holds the address of the data.

Referencing 

Dereferencing 

Example 

$ref = \ %students;

%{$ref} 

%{$recAddr}->{“Name”}

$database[$i]->{“Name”} This is shortcut, while perl handling original %{$database[$i]}->{“Name”}

$ref = \&swap;

&{$ref} 

&{$func} (\$a,\$b); 

$ref = \@array;

@{$ref} 

@{$arrayOne}[1]; 

 

How do you identify the type of Reference?

Function ref($refVariable) return a string indicating the type.

Function Call 

Return Value 

ref(10) 

undefined 

ref(\10) 

SCALAR 

ref(\%students) 

HASH

ref(\&swap) 

CODE 

Ref(\\10)

REF 

 

How to you send two arrays to a subroutine?

Since array is exhaustive while retrieving parameters in the subroutine

(@arr1,@arr2) = @_;     # @arr1 consumes complete list @_ leaving nothing to @arr2

Thus we use references here

Calling function

 

print(\@a, \@b);

 

Callee function

 

sub print{

    my ($arr1, $arr2) = @_;

    print “Array1: @{$arr1}\n”;

    print “Array2 top: @{$arr2}[0]“;

}

Referencing Functions

my $func;

    chomp($choice=<STDIN>);

    {        #implementing switch case

        $choice==1 && do {$func=\&add; last;};

        $choice==2 && do {$func=\&swap; last;};

        print “Enter valid choice”;

    }

    

    &{$func} (\$a,\$b);     #CODE Reference

 

Working with Associative Arrays / Multi-dimensional Arrays

 

Complex data structures are implemented in C using Pointers, in the same fashion mult-dimentional arrays / associative arrays are implemented using References.

 

A 2D array is an array having references of various arrays.

 

my @matrix = ( [1,2],    

             [2,3] );

    This is accessed as @matrix[1]->[0], since @matrix[1] óAddress of [2,3]

    This also can be referenced as $matrix[1][0]

 

Here is an Example of using Associative Arrays

 

Array of Records

sub addStudent{

    

    my %rec;

    

    %rec->{“Name”} = $_[0];

    %rec->{“Address”} = $_[1];

    
 

    

    my $index = scalar @database;    #specifying scalar explicitly is not required

    $database[$index] = \%rec;

}

 

sub printRecords{

    my $i=0;

    

    for($i=0; $i<scalar(@database); $i++){

        print “\n\nName\t: “.$database[$i]->{“Name”};    # this is shortcut

        print “\nAddress\t: “.$database[$i]->{“Address”};

    }

}

 

    

 

 

@database = (

{ “Name” => “Jane Hathaway”,

“Address” => “123 Anylane Rd.”

},

{ “Name” => “Kevin Hughes”,

“Address” => “123 Allways Dr.”

}

);

 

printRecords();

addStudent(“Mahesh”,”Hyderabad, AP”);

printRecords();

 

 

sub searchStudent{

    

    print “Total record present: “.scalar(@database).”\n”;

    print “Enter whose record: “;

    chomp($name=<STDIN>);

 

    foreach $recAddr (@database){

        if( %{$recAddr}->{“Name”} =~ /\b$name\b/i ){

            print “Record Found”;

        }

    }

    

} 

 

$database[$index] returns address of Record stored as Hash.

So Record is accessed as
%{ $database[$i] }->{“Name”}
since it is cumbersome, perl handles it and in short
$database[$i]->{“Name”}

 

 

Using Associate Array to Hold Records

%database = (

“MRD-100” => { “Name” => “Jane Hathaway”,

“Address” => “123 Anylane Rd.”,

“Town” => “AnyTown”,

“State” => “AnyState”,

“Zip” => “12345-1234”

},

“MRD-250” => { “Name” => “Kevin Hughes”,

“Address” => “123 Allways Dr.”,

“Town” => “AnyTown”,

“State” => “AnyState”,

“Zip” => “12345-1234”

}

);

 

print(%{$database{“MRD-100”}}->{“Name”} . “\n”);

 

Here Like a normal hash $database{“MRD-100”} returns the address of a record stored as associate array.

Hence to access the record (hash), having the record address

%{ addr }->{ key } ó %{$database{“MRD-100”}}->{“Name”}

 

 

Interpolating Functions

 

Functions returns values. If we want to print those values directly in print, we can use address of the value returned by the functions

 

    print “Sqaure = ${\square($i)}”;

 

 

Advertisements

About Uma Mahesh

A Creator/Equilizer. Creator/Equalizers are catalysts for positive, well-organized change. They never settle for the status quo. Instead, they see the opportunity for innovation in the processes that others have long taken for granted. They respect what's already operating, but they can't help but want to improve upon it. Their special combination provides innovation tempered with profound logic. They have incredible discernment. Should their efforts fail, they are unhesitating in accepting responsibility. They don't wallow in self-pity but rather see these missed attempts as critical steps on the path to success.
This entry was posted in Notes, Tutorials and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s