[Ilugc] [TIP] perl tutorial XI (perl references)

  • From: girishvenkatachalam@xxxxxxxxx (Girish Venkatachalam)
  • Date: Wed, 14 Dec 2011 17:47:31 +0530

Well just a reference would not cut it.

In English the language that I am not a master of and neither would I
want to be a
 master of come what may, there are two words.

Infer
Imply

Both mean more or less the same thing. You say, implied meaning and you say,
 "I infer from this the following."

Anyway in programming languages references or pointers and the C
language idea of
 call by reference and call by value all have something to do with
what I wrote above in
 English.

Basically the concept is that in the normal idea in which a variable
holds a value, like

$a = 50;

in the case of a reference or a pointer, you have a certain
associativity as in math like this:

a -> b -> c

a - (refers to) -> b - (refers to) -> c

So you say something like this in perl.

$a = 50;
$ref = \$a;

So now it is like this:

$ref -> $a -> $50

So you can easily dereference $ref and say,

${$ref} and you will get 50.

As you can see a scalar reference is not like a C variable pointer. It
is not that
 useful.

What makes us wonder at perl's genius and the cleverness of the design is in
assigning an array pointer.

Like this:

@a = (1,3,4,40);

$aref = \@a;

Now it is fun.

You can do a lot of cool things with it but that will take time. For
now say, you can
do this:

print @{$aref};

And as you can guess you can pass the entire array in one variable by
passing a reference to it.

There are lot of other very useful clever things you can do too.

You can build an array of references.

@refarray = ($aref, $aref2, $aref3);

where,

$aref = [1,3,4,10];
$aref2=[2,3,4,200];
$aref3=[100,"girish", 20];

Now you have what can be argued is a 2 dimensional array.

Hmm, things are getting a bit involved no?

Hold on. Be with me.

But before that how do these become array references? I just changed the
 () to [] and how do these become references?

That is a perl idiom. Always use funny characters to say what you mean.

So instead of :

@a = (1,3,4);
$ref = \@a;

you say,

$ref = [1,3,4];

Now to dereference you say,

@a = @{$ref};

You can obtain a reference with:

\

and you can dereference with:

@{ }

Try examples.

$ perldoc perlref

-Girish
-- 
G3 Tech
Networking appliance company
web: http://g3tech.in ?mail: girish at g3tech.in

Other related posts:

  • » [Ilugc] [TIP] perl tutorial XI (perl references) - Girish Venkatachalam