PERL/C3/Referencing-and-Dereferencing/English
Title of script: Referencing and Dereferencing in Perl
Author: Nirmala Venkat
Keywords: Scalar References, Array References, Hash References, Dereferences, video tutorial
|
|
Slide 1: | Welcome to the Spoken Tutorial on Referencing and Dereferencing in Perl. |
Slide 2:
Learning objectives |
In this tutorial we will learn about
|
Slide 3:
System Requirements |
For this tutorial, I am using
You can use any text editor of your choice. |
Slide 4:
Pre-requisites |
You should have working knowledge of
If not, then go through the relevant Perl spoken tutorials on this website. |
Slide 5: | What is References?
A reference is a pointer or an address to a variable, array, hash or a subroutine. It does not contain data directly. Reference is an easy, compact scalar value. |
Slide 6:
|
Reference will improve the performance of Perl code when you pass or return large data structures.
It saves memory as it passes a reference to a subroutine rather than passing a value. Easy to manage complicated Perl data structures. |
Let us learn how to create a reference. | |
Slide 7:
Reference to a scalar variable: ($) $fvalue = 22; $fref = \$fvalue; Reference to a array variable:(@) my @color =('Red', 'Green', 'Yellow'); $colorRef = \@color; Reference to a hash variable:(%) %dept( Name => “Sunil”, Designation => “Manager” ); $deptRef = \%dept; |
We can create a reference for any variable, subroutine or value, by putting a backslash (\) in front of it.
A scalar variable is referenced by backslash and dollar sign ($) as shown here. An array variable is referenced by backslash and at the rate(@) symbol. A hash variable is referenced by backslash and percentage(%) symbol as shown in the example here. |
Slide 8: | When a reference is dereferenced, the actual value is returned.
Dereference is done by enclosing the reference variable within curly brackets. And preceding the left curly bracket with a character denoting the type of reference it is. |
Let us see how to dereference variables. | |
Slide 9: | A scalar variable is dereferenced by dollar sign ($) and curly brackets.
An array variable is dereferenced by at the rate (@) symbol and curly brackets. A hash variable is dereferenced by percentage(%) symbol and curly brackets. |
Let us see a simple program for Scalar reference and dereference. | |
Switch to the file in gedit. | Let me open a sample program in gedit Text editor. |
Switch to the Terminal and type
gedit scalarRef.pl & |
Open the terminal and type gedit scalarRef dot pl ampersand
and press Enter. |
Point the cursor to
scalarRef.pl |
Type the following code as displayed on the screen in the scalarRef dot pl file. |
#!/usr/bin/perl
$a =10; # Now $aref has reference to $a scalar. $aref = \$a; # Print value available at the location stored in $aref. print "Value of ‘aref’ is: ",$aref, "\n"; print "Value of a is : ", ${$aref}, "\n"; print "Reference type is : ", ref($aref), "\n"; |
Let me explain the code.
First line declares a scalar variable '$a' and initialized to 10. As mentioned earlier, a scalar variable is referenced by backslash and dollar sign ($) This line will print memory address of the variable that is created as reference. To print the actual value, the variable is dereferenced by curly brackets preceded by $. ref() function will return the reference type such as scalar or array or hash. |
Press Ctrl+S | Now, press Ctrl+S to save the file. |
Let us execute the program. | |
Switch to terminal
perl scalarRef dot pl |
Switch to the terminal and type
perl scalarRef dot pl and press Enter. |
Highlight | The output is displayed as shown.
First line shows the memory address where the value 10 is stored. The second line returns the actual value 10. Ref() function returns 'Scalar' as output. |
Next, let us understand how to create a reference and dereference array by using a sample program. | |
Switch to the file in gedit. | I already have a sample program.
Let me open it in gedit Text editor. |
Switch to the Terminal and type
gedit arrayRef.pl & |
In the terminal, type gedit arrayRef dot pl ampersand
and press Enter. |
Point the cursor
arrayRef.pl |
Type the following code as displayed on the screen in the arrayRef dot pl file. |
Highlight in gedit
#!/usr/bin/perl use strict; use warnings; my @color = ('Red', 'Green', 'Yellow'); my $colorRef =\@color; print "Reference: $colorRef\n"; print "Dereferenced: @{$colorRef}\n"; |
Let me explain the code now.
Here, in the first line, I have declared an array @color and initialised it with three values. It is referenced with backslash @color which is the array name and assigned to $colorRef. The print statement will print the reference value and the dereferenced value. |
Now, press Ctrl+S to save the file. | |
Let us execute the program. | |
Switch to terminal
perl arrayRef dot pl |
Switch back to the terminal and type
perl arrayRef dot pl and press Enter. |
Highlight
Output |
The output is displayed as shown here
Reference: ARRAY(0x81e4638) Dereferenced: Red Green Yellow |
Highlight first line
Highlight the second line |
The first line shows the output of the memory address of the variable that is created as reference.
The second line shows the actual value that is dereferenced. |
Next, we will see how to declare direct or anonymous reference for an array.
Let’s come back to our program. I have changed the existing program to show the direct reference for an array. | |
Highlight
my $colorRef = ['Red', 'Green', 'Yellow']; Use arrow operator (->) to dereference. print $colorRef ->[1]; |
You can create a direct reference to an array by using square brackets [] as demonstrated.
Use arrow operator (->) to dereference. Print statement will print 'Green' as output. Here the print statement takes the value of index[1]. i.e Green in our program. |
Now, press Ctrl+S to save the file. | |
Switch back to the terminal and type
perl arrayRef dot pl and press Enter to execute. | |
Highlight the output | <<PAUSE>> |
I’ll show an example on how to use the direct hash reference in the same code file. | |
Open the gedit and paste the below code. | So, let’s switch to gedit. |
Highlight in gedit
my $deptRef = { Name => “Sunil”, Designation=>“Manager”}; print ${$deptRef} {Name}; or print $deptRef -> {Name}; Output: Sunil |
You can create a direct reference to hash by using curly brackets {} as shown here.
Use arrow operator (->) to dereference it. “Name” is the hash key. On executing this block of code, both the print statements will print 'Sunil' as output. |
Next we will see how to add, remove, access elements to array reference with a sample program. | |
Switch to the file in gedit | I already have a sample program.
Let me open it in gedit Text editor |
Switch to the Terminal and type
gedit arrayRefadd .pl & |
Open the terminal and type gedit arrayRefadd dot pl ampersand and press Enter |
arrayRefadd.pl file is now open in gedit.
Type the code as shown here in your file. | |
Highlight in gedit
#!/usr/bin/perl use strict; use warnings; # initialize an array my @numarray = (1, 2, 3, 4); # get a reference to it my $ref = \@numarray; # Apply Accessing an element print "First element:", $ref->[0], "\n"; # apply push (append a few elements) push(@$ref, 5, 6, 7); # or push @{$ref}, 5, 6, 7; # print the array using the reference print "After adding:" ,@{$ref},"\n"; # it displays 1 2 3 4 5 6 7 # apply pop (remove an element) pop(@$ref); # print the array using the reference print "After deleting :",@{$ref},"\n"; |
The first line initializes an array.
We have referenced an array with backslash @numarray and assigned to $ref. Now, we will see how to access a particular element from the array reference. We need to use the array index in square brackets “[ ]” to access the particular value. And an arrow operator (“->”) to dereference it. The print statement will print the value of index[0] Push function adds elements at the last position of an array reference. In our case 5,6,7 is added to at the end of the existing array 1,2,3,4. Print statement shows the output after adding to the array reference. Pop function removes an element from the last position of an array reference In our example, 7 will be removed from the existing array reference. Print statement shows the output after deleting from the array reference. |
Now, press Ctrl+S to save the file. | |
Let us execute the program. | |
Switch to terminal
perl arrayRefadd dot pl |
Switch back to the terminal and type
perl arrayRefadd dot pl and press Enter. |
Highlight the output:
First element:1 After adding:1234567 After deleting :123456 |
The output is displayed as
First element:1 After adding:1234567 After deleting :123456 |
Now let us see another sample program to add, remove, and access elements of hash reference. | |
Swtich to the Terminal and type
gedit hashRefadd.pl& |
Switch back to the terminal and type
gedit hashRefadd dot pl ampersand |
Point to the filename hashRefadd.pl in the Titlebar of gedit. | This will open the file hashRefadd.pl in gedit.
Let me explain the sample program. |
#!/usr/bin/perl
use strict; use warnings; my $weektemp = { monday => 40, tuesday => 38, wednesday => 36, thursday => 39, friday => 41, }; # Print all foreach my $keys(keys %$weektemp) { print "$keys: " . $weektemp->{$keys} . "\n"; } Highlight #Print Temp on monday my $monday_temp= print "First day temp is: " . ${$weektemp}{monday} . "\n"; |
I have declared a direct hash reference that can be stored in a scalar variable $weektemp.
I have used curly brackets to represent the hash reference and the arrow operator to dereference. This code stores the temperature values from Monday to Friday. I am using the “keys” built-in function to loop through the keys of the hash. Print statement will print each element of the hash. We can access the particular value of an element as shown here. Print statement will print the temperature on Monday. |
Now, save the file. | |
Terminal | Switch to terminal and type-
perl hashRefadd dot pl and press Enter to see the output. |
Highlight output:
friday: 41 wednesday: 36 thursday: 39 tuesday: 38 monday: 40 |
The hash keys and hash values are stored in a random order.
The displayed output is not related to the order in which they were added. Go through the code once again to understand why this is so. |
With this, we come to the end of this tutorial.
Let us summarize. | |
Slide 10:
Summary
|
In this tutorial, we learnt about:
|
Slide 11:
Assignment |
Here is an assignment for you.
|
Slide 10:
About Spoken Tutorial project
|
The video at the following link summarises the Spoken Tutorial project.
Please download and watch it |
Slide 11:
Spoken Tutorial workshops |
We conduct workshops and give certificates for those who pass our online tests.
For more details, please write to us. |
Slide 12:
Acknowledgement
|
Spoken Tutorial project is funded by NMEICT, MHRD, Government of India.
this link. |
This is Nirmala Venkat from IIT Bombay, signing off. Thanks for watching. |