CIW Course Revision Site


Perl - References

In a Nutshell - CIW Course Section 2, Part B2, Chapter 5

 

References

References in Perl are not letters of recommendation! They would be much easier to understand if they were. I struggled through this part of the course, without really understanding any of it. But, returning to it now to try and produce this page has involved some serious revision.

Having read through this chapter several times, I can now see what is being done and how it is being done. I can't, however, see why! I think better examples would have simplified the understanding.

I find the easiest way to think of a reference, is as a pointer. A reference is a scalar value that is, essentially, the address of the referenced item in memory.

$varRef = \$var;
$arrayRef = \@array;
$hash_Ref = \%hash;

Where I felt the course began confusing the issue, was with the use of anonymous hashes and arrays. Useful to know about them, but here; they just muddied the waters.

$arrayRef = ["Val1", "Val2", "Val3"];
$hash_Ref = { key1=>"val1", key2=>"val2"};

Notice the different syntax when defining these anonymous objects. They are anonymous as they don't have a name, or a named instance, only a reference. The same objects defined as named instances would look like this:

@array = ("Val1", "Val2", "Val3");
%hash = ("key1"=>"val1", "key2"=>"val2");

Having created an array or a hash we can still use a reference to it. By using the backslash "\" character we can instruct Perl to use a reference to the object, rather than the object itself. So \@array uses a reference to the array.

Why would you use a reference? This is where my understanding gets a little bit flaky. Going back several years to when I dabbled with the 'C' programming language which uses pointers to data structures, passing a data structure to a subroutine involves transferring or copying the entire structure. If the data structure is large this can have a considerable impact on performance. Passing a pointer is far more efficient as the original structure remains unchanged in memory.

I can only assume that Perl treats references in much the same way.

The example from the course manual shows how passing references to a subroutine will create local copies of the references within the subroutine, and de-referencing these will allow manipulation of the data. It should be remembered that the data being manipulated is the original data as while this method creates copies of the references, it does not create copies of the data.

 

Design by Stephen

Certified Internet Webmaster

Page last Edited: 10 Nov 2011