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

Re: [MacPerl] Multidimensional array question



>Question about multidimensional arrays.  I believe I know the answer to
>this but want to make sure.
>
>Why does:
>
>	$a[++$#a][0] = x;
>	$a[$#a][1] = y;
>
>Not work?  I get back:
>
>	ARRAY(blah,blah,blah)
>
>instead of the value of "x".
>
>My theory is that with multidimensional arrays you have to do the
>increment outside of the array because otherwise the pointers are not in
>place before the values are used.  Like so:
>
>	$#a++;
>	$a[$#a][0] = x;
>	$a[$#a][1] = y;
>
>At least, the first example gives me back that ARRAY stuff and the
>second one gives me back my values.

Perl (and I may stand corrected), like C, does not actually support
multi-dimensional arrays.  What is does support are arrays that may be of
any Perl type, including arrays and hashes.  Thus technically we would be
talking about an array of arrays.  This bit of info may be useless, but I
had to mention it.

Now, part of the problem may be that the two bits of code you present
actually do different things.  Assuming for the sake of exposition that @a
is an array of one element ($#a==0) before the code is called.  If the
array is undefined or empty, an error should be generated since $#a of an
empty array is -1:

The first piece of code assigns the value of x to the 1st element of the
array @{$a[0]}, then an (undefined) element is added to the end of array @a
(making two elements and $#a==1).  Next, the 2nd element of the array
@{$a[1]} is assigned the value of y.  This action defines $a[1] as an array
of two elements.  The second piece of code (making the same assumptions
about @a) adds an element to @a (making $#a==1) then assigns the first
element of @{$a[1]} to x, and the second to y.  As these code fragments do
not correspond I would assume that the second action is what you truly
intend to do, a more elegant way of doing it would be:
	push @a, [ (x, y) ];
Thus you always add to the end of @a and avoid an undefined @a and
"skipping" elements.

-Alex



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