[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Multidimensional array question



>Yes, I'm replying to my own message. :-) After rereading it, I realize
>that something I was trying to imply didn't come through at all and I
>should have just stated it. That is, because perl multidimensional arrays
>aren't the same as multidimensional arrays in other programming languages
>(I would argue they're much better), the size of the second and subsequent
>subscripts *depends upon the value of the first subscript*.

More specifically, Perl does not support multi-dimensional arrays.  It
supports arrays where each element can be a string, a number, array, hash,
or reference, and any combination thereof.  Elements that are arrays or
hashes are actually anonymous references (after a fashion) and must be
de-referenced (hence the use of curly braces) to be used.  Thus,
$array[x][y] is actually only shorthand for ${$array[x]}[y].  Further, each
element of an array could be an array of varying lengths (which is the
point I think Brian is making).

>Consider:
>
>$m[0] = 'Greetings, earthling.';	# myArray's too hard to type :-)
>$m[1][23] = 42;
>$m[2] = {'a' => 4, 'b' => 3};
>$m[3][5] = 23;
>
>Then,
>
>$#m == 3 && @m == 4
>$#{$m[0]} isn't defined and will result in a runtime error

Really, $m[0] is a string and not a reference, thus it cannot be dereferenced.

>$#{$m[1]} == 23 && @{$m[1]} == 24
>$#{$m[2]} isn't defined and will result in a runtime error

Ditto for $m[2] (number, not reference).

I think it best to not even use the term "multidimensional", as Brian's
example shows that this is not the case and it can cause mysterious bugs.
Instead, I find it much better to think of "arrays of arrays", or better
yet, "arrays of references to other arrays", rather than "multidimensional
arrays".  It makes working with complex data structures much more
comprehensible.

-Alex



***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch