Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

comment on

( [id://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;
prints:
    ARRAY(0x1a6527c)

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;
prints:
    ARRAY(0x1a6527c)ARRAY(0x1a6527c)

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];
prints:
    1

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";
prints:
    one 2 3 four (*disclaimer:
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];
prints:
    1 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];
prints:
    1

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 [ ].

Named:
my @array1 = (1, 2, 3, 'four'); my $reference1 = \@array1;
Anonymous:
    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];
As:
my @array = ( [1, 2, 3, 'four'], ['one', 'two', 'three', 4] ); print $array[0]->[0];
prints:
    1
"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

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (9)
As of 2024-03-28 10:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found