Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
Can any one explain me how to handle multidimensional array?

Well, let's just quickly review what an array is. An array is a variable that holds a list of scalar values.

    my @array = (1, 2, 3, 'four');

To access a single element of this array, we use a subscript. In perl a subscript is enclosed in square brackets [ ]. To print the first element of @array we write:

print $array[0]; ^

We use the scalar ($) prefix because we are referring to 1 value and we use a subscript of 0 because all arrays start with 0 as the first item (unless we change the value of mumble mumble mumble, which is deprecated).

Since an array can only hold a list of scalar values, it cannot hold an array (which is not a scalar) and multidimensional arrays are not possible in perl.

Let's take a short intermission here while we catch our breath.

This break is being sponsored by that wonderful little scalar - The Reference.

If you have done any assembler programming, you are familiar with indirect addressing. References are similar. (Okay, maybe not.) They allow us to refer to a scalar, array, hash, or any object indirectly.

What's more, they allow us to refer to these variables with a single scalar value. (Sort of like referring to a human as 'her' instead of 'that drop dead gorgeous blonde Gertrude Rose Bertrand'.)

Let's take a look at a reference to an array. To reference @array, we precede it with \:

my @array = (1, 2, 3, 'four'); my $reference = \@array; print $reference;

Note, that if we increase the size of @array by 1000 elements, the reference stays the same:

my @array = (1, 2, 3, 'four'); my $reference = \@array; print $reference; push @array, (1 .. 1000); $reference = \@array; print $reference;

We can refer to an element of an array reference with the arrow (->) notation:

my @array = (1, 2, 3, 'four'); my $reference = \@array; print $reference->[0];

Oh another thing, a reference refers to the original variable, if you change an element in a reference you also change it the original variable or object which is sometimes referred to as the referent.

my @array = (1, 2, 3, 'four'); my $reference = \@array; $reference->[0] = 'one'; print "@array";
    one 2 3 four
all variables in the preceding examples
are fictitious. Any resemblance to real
variables is purely coincidental. References
will not be directly (or indirectly) liable for
any similarities to real variables.)

This preceding break was sponsored by that wonderful little scalar - The Reference.

Well, now that your finished buying your popcorn and staring at that drop dead gorgeous blonde Gertrude Rose Bertrand. Let's look at a way to have multidimensional arrays and still use perl.

You may want to read a little about references before continuing. Perlref has some stuff in it you'll find useful. (I'm far to busy to mention them here!)

Since a reference is a scalar and an array holds a list of scalars, an array could hold a list references. Now, an array reference can refer to an element of the array it refers to with the arrow notation (->) just like we did with @array before the intermission.

Let's review:
my @array = (1, 2, 3, 'four'); print $array[0];
prints:     1
my @array = (1, 2, 3, 'four'); my $reference = \@array; print $reference->[0];
And for more than one dimension:
my @array1 = (1, 2, 3, 'four'); my $reference1 = \@array1; my @array2 = ('one', 'two', 'three', 4); my $reference2 = \@array2; my @array = ($reference1, $reference2); # this refers to the first item of the first array: print $array[0]->[0];

Okay. $array[0] refers to $reference1 and a reference to an array can use arrow notation to refer to it's elements.

$reference1->[0] refers to @array1's first element. Using a little algebra we can replace like terms. $reference1 = $array[0], so $reference1->[0] is the same as $array[0]->[0].

(Please, take a moment to write a nice email to your under appreciated algebra teacher. We'll wait for you.)

You wrote to Gertrude, didn't you? (Shame!)

Let's take a look at a reference to an array that has no name. A nameless array is (drum roll, please) anonymous. An anonymous array in perl is constructed using square brackets [ ].

my @array1 = (1, 2, 3, 'four'); my $reference1 = \@array1;
    my $reference1 = [1, 2, 3, 'four'];
So we could rewrite:
my @array1 = (1, 2, 3, 'four'); my $reference1 = \@array1; my @array2 = ('one', 'two', 'three', 4); my $reference2 = \@array2; my @array = ($reference1, $reference2); print $array[0]->[0];
my @array = ( [1, 2, 3, 'four'], ['one', 'two', 'three', 4] ); print $array[0]->[0];
"Trust in the Algebra, Luke"

Perl allows us to drop the -> between subscripts, so we can also write this as:

my @array = ([1, 2, 3, 'four'], ['one', 'two', 'three', 4]); print $array[0][0];
prints:     1

Perldsc has a section titled 'ARRAYS OF ARRAYS' that gives more examples of declaring and generating an array of array references (a.k.a. multidimensional arrays). Note that an array can contain references to arrays of differing sizes:

my @shapes = ( [qw/circle square triangle polygon/], [qw/red green blue yellow fuschia/] );

Data::Dumper provides a the Dumper sub which will print an array of array references. This is a great debugging tool:

use Data::Dumper; print Dumper \@shapes;

Here's the output one array:

$VAR1 = [ [ 'circle', 'square', 'triangle', 'polygon' ], [ 'red', 'green', 'blue', 'yellow', 'fuschia' ] ];

Finally, take a look at Perllol which describes Manipulating Arrays of Arrays in Perl and Perldata, especially the part about slices (and apple pie).

"The only dumb question is the one you fail to ask."

Update (2 FEB 2009): Fixed a typo and changed array name.

Update (5 JUN 2012): Added missing code tags around Data::Dumper code.

In reply to Multidimensional Arrays by CharlesClarkson

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, 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, 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.
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others about the Monastery: (3)
    As of 2020-02-29 01:54 GMT
    Find Nodes?
      Voting Booth?
      What numbers are you going to focus on primarily in 2020?

      Results (128 votes). Check out past polls.