You can't really have nested arrays the way you seem to think about them in Perl. An array is just a collection of ordered scalars. So, if you try to do something like this:

my @master_array = (1, 3, (5, 9, 4), 2, (8, 7), 6);

you will not get an array of arrays, but just a flat array containing all the values listed above, just as if you had declared it this way:

my @master_array = (1, 3, 5, 9, 4, 2, 8, 7, 6);

But you can nonetheless build nested data structure by the use of references: some of the scalars of your array might be references to other arrays.

For example you could do this:

my @subarray1 = (5, 9, 4); my @subarray2 = (8, 7); my @master_array = (1, 3, \@subarray1, 2, \@subarray2, 6);

Here, $master_array[2] contains \@subarray1, which is a scalar containing a reference to the @subarray1 array. You could now access the 9 value with the following syntax:

my $value = $master_array[2][1];

To change 9 to 10, just use it the other way around:

$master_array[2][1] = 10;

You can also use the [] array reference constructor to obtain the same result:

my $subarray1_ref = [5, 9, 4]; my @master_array = (1, 3, $subarray1_ref, 2, [8, 7], 6);

This gives you a first idea about what you can do, but you definitely need to read the documentation about Perl references and data structure to go further. The place to start is the Perl Data Structure Cookbook: http://perldoc.perl.org/perldsc.html.


In reply to Re: Arrays in arrays, how to access them by Laurent_R
in thread Arrays in arrays, how to access them by viored

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.