Subscribe Add to Technorati Favorites

Wednesday, July 2, 2008

PERL References


Familiar with C pointers?

In C pointers are variables that contains the location of some other piece of data. That is, it can be a machine address.

In similar lines PERL also supports pointer variables called references.

If you do not understand the pointer concept, here is an illustration (I had read this in a book on 8085, long back):
Take a look at the picture above.

The image is self explanatory, cup c1 analogous to a pointer variable has a piece of paper that has the name of another cup (
address) that has the juice which is cup c2.

Similarly, in PERL consider c1 is the reference to variable c2. These references can point to a scalar/array/hash/a subroutine.

Syntax:
my $scalar_ref = \$scalar_a;
my $array_ref = \@array_a;
my $hash_ref = \%hash_a;
my $sub_ref = \&find_average;

Here the slash (\) operator is used to create references. References can be anonymous too, that is without any name. Anonymous hashes can be used to create complex data structures such as array of hashes, hashes of hashes, etc

Also references can be created to file handles & type globs.

References are just like other scalar variables. Perl also offers a function ref() to check the type of reference a scalar holds. For example:

$ref_type = ref($scalar_ref);

ref() returns (without double-quotes)
"SCALAR" for scalar refs
"ARRAY" for arrays
"HASH" for hash
"CODE" for subroutine
It returns undef for a scalar variable. For more info on this you can visit: http://perldoc.perl.org/functions/ref.html

And for more info on references, visit: http://perldoc.perl.org/perlreftut.html

0 comments: