[Ilugc] [TIP] perl tutorial XII (hashes and references)

  • From: girishvenkatachalam@xxxxxxxxx (Girish Venkatachalam)
  • Date: Thu, 15 Dec 2011 09:52:39 +0530

References in perl are nothing but pointers but you can't use it like
you do it in C with subtraction, increment and so on.

Perl is a higher level language the references have to be used the perl way.

For instance references allow us to have a hash of arrays. A big array
can be coverted into one element easily with a reference
 and you can use that as a value in a hash.

For that matter you can even use function pointers are hash values.
This is in fact a common perl idiom. Of course in perl you
 don't call it a function pointer; instead you say subroutine reference.

Anyway now let us look at a hash.

%h = ( 1 => "first", 2 => "second );

$h{1} is "first" and $h{2} is "second".

Now

%h = ( 1 => [1,2,45,100], 2 => $a);

$a = [1,100,"girish"];

Of course the second line should come on top of first.

Now you can do like this:

$aref = $h{1};

@arr = @{$aref};

You can build an array of references like this also.

@a = (1,2,3,4, [10,30,4], [1,3,4]);

$a[#a][0], $a[#a][1], $a[#a][2] will give 1,3,4

You can also obtain a reference to a hash.

%hs = ( 123 => 35, 100 => 20);

$ref = \%hs;

%hash = %{$ref};

Now, $hash{123} will give 35.

$ perldoc perllol

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

Other related posts:

  • » [Ilugc] [TIP] perl tutorial XII (hashes and references) - Girish Venkatachalam