my @array = (["w", "h", [1, 2], "c"]);

First of all you should realize that the above code creates a one element array that contains a reference to a 4 element array. The square brackets indicate that you are creating or returning a reference to an array so you end up with a three dimensional array. You probably intended to use ("w", "h", [1, 2], "c") which would give a two dimensional array. Your code is perfectly legal, but probably not what you expected.

So with your original code $array[0] will contain a reference to a four element array. To look at the first element in this array, you have properly dereferenced it by using the -> operator and that is why $array[0]->[0] returns "w".

Now $array[0]->[2] contains a reference to your embedded array, so to access the the elements of this array, you must dereference again, by using the -> operator again. So $array[0]->[2]->[0] contains the number 1 and $array[0]->[2]->[1] contains the number 2.

The reason you are seeing ARRAY(0x1770fa) when you print $array[0]->[2] is because that contains the reference to the array [1, 2]. The value that a reference contains is the memory location of the actual array that it points to, and that is what is printed out.

Just remember that [] always returns an array reference and needs to be dereferenced to access it.


In reply to Re: Multi dimensional arrays by cees
in thread Multi dimensional arrays by phatbasturd

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.