Wednesday 2 December 2009

Multidimension reference and dereference

Slices and arrays (multi-dimension - referencing and dereferencing ) :

As mentioned previously, every array or hash in Perl is implemented in one dimension."Multi-dimensional" arrays, too, are one-dimensional, but the values in this one-dimensional array are references to other data structures. If you print these values out without dereferencing them, you will get the references rather than the data referenced. For example, these two lines:

@LoL = ( [2, 3], [4, 5, 7], [0] );

print "@LoL";

result in:

ARRAY(0x83c38) ARRAY(0x8b194) ARRAY(0x8b1d0)

On the other hand, this line:

print $LoL[1][2];

yields 7 as output.

Note :
Perl dereferences your variables only when you employ one of the dereferencing mechanisms. But remember that $LoL[1][2] is just a convenient way to write $LoL[1]->[2], which in turn is a convenient way to write ${$LoL[1]}[2]. Indeed, you could write all your dereferencing operations with braces, but that would be uglier than ugly. Use the syntactic sugar Perl provides to sweeten your program.

@LoL above was defined as an array whose values happened to be references. Here's a similar-looking, but very different case:

my $listref = [

[ "fred", "barney", "pebbles", "bambam", "dino", ],
[ "homer", "bart", "marge", "maggie", ],
[ "george", "jane", "elroy", "judy", ],

];

To access "elroy" element of third array , print $listref[2][2]; # WRONG!

Here, $listref is not an array, but a scalar variable referring to an array - in this case, referring to an anonymous, multi-dimensional array, the one created by the outer brackets. Therefore, to print elroy in this example, we should have said:

print $listref->[2][2];


No comments:

Post a Comment

Tweets by @sriramperumalla