• Home   /  
  • Archive by category "1"

Perl 2d Array Assignment In C

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.

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:

[download]

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 \:

[download]

prints:

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

[download]

prints:

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

[download]

prints:

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.

[download]

prints:
(*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:

[download]

prints:

[download]

prints:
And for more than one dimension:

[download]

prints:

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

refers to @array1's first element. Using a little algebra we can replace like terms. , so is the same as .

(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:

[download]

Anonymous:
So we could rewrite:

[download]

As:

[download]

prints:
"Trust in the Algebra, Luke"

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

[download]

prints:

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:

[download]

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

[download]

Here's the output one array:

[download]

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.

Re: Multidimensional Arrays
by chipmunk (Parson) on Jun 22, 2001 at 20:18 UTC
    The syntax is unsupported; it was never really intended to work in the first place.

    The perldelta that comes with 5.6.1 explains:

    [download]

    I think that your tutorial is somewhat misleading, because you seem to suggest that is a standard idiom.
[reply]
[d/l]
[select]

      Well, I haven't gotten aroud to installing 5.6.1 and I probably would have missed this. Would you mind rereading the tutorial. I edited it with your comment in mind and would like to know if it screwed up the logical flow.


      Thank You,
      Charles
[reply]
        great tutorial. I was really struggling trying to grasp the concept, I had read everything I could, but nothing seemed to sink in until I read this article! Charles, you have a gift. I almost did not read the article due to the name, perhaps you could mention reference. I wish some of the posts on why NOT to use symbolic references had a link to this article... Another intersting chapter might be using hashes in a reference.
[reply]
Re: Multidimensional Arrays
by Anonymous Monk on May 28, 2003 at 07:47 UTC
    Beautiful description. I too have tried over and over to learn this. I ended up creating a moc multi-dimentional array with a hash:

    # dbl Quotes required!

    I can iterate through the array answers for Q1 like this:

    As an added benefit, I can also create other "properties":

    So, that makes it sort of like a virtual object, which I need to learn someday. This was great. Thanks again. -sleve

[reply]
[d/l]
[select]
Re: Multidimensional Arrays
by vili (Monk) on Jul 22, 2003 at 23:58 UTC
    Useful, and to the point.
    Thanks fo taking the time.
    ~vili
[reply]
Re: Multidimensional Arrays
by Sameet (Beadle) on Apr 30, 2004 at 06:25 UTC
    Hi, I am a newbie, and this node was surely very useful. Thank you
    Sameet
[reply]

      You're welcome. Glad you liked it.

[reply]
Re: Multidimensional Arrays
by Anonymous Monk on Aug 25, 2004 at 02:19 UTC
    Thanks for this tutorial, a quick google search lead me to this page. Got the answer I needed faster than by searching the perl docs.

    I was trying...
    ;
    but that didn't work.
    What I needed was

    so that I can read a value directly with


    Thanks again.

[reply]
[d/l]
[select]
Re: Multidimensional Arrays
by Anonymous Monk on Mar 18, 2003 at 22:21 UTC
    I hate to pick nits...no, wait. I love to pick nits. Well, nevermind then. What I mean is, to be accurate, "Using a little algebra we can replace like terms." is incorrect. $reference1 and $array[0[]] aren't like terms at all, they're entirely different variables. They *are* equal terms. Maybe we should email *your* algebra teacher... :)

    Hey! Are you even listening? Hello? Oh, put the picture down already!
[reply]
Re: Multidimensional Arrays
by Anonymous Monk on Nov 25, 2004 at 09:29 UTC

    [download]

    what am i doing wrong ?
[reply]
[d/l]
      You could try:

      [download]

      using an array to hold the row, or:

      [download]

      using a ref to the row. You should also consider , BTW...
[reply]
[d/l]
[select]

      has a single element - a reference to a reference to an array.

      Try:

      Update: fixed typo

[reply]
[d/l]
[select]
        This works, too:

        [download]

        I think ist is a little bit clearer (from in to out): 1. fetch array element 0, 2. dereference, 3. treat it like an array, 4. fetch via .

        But this all looks really ugly. It would be better to fix the strange assignment to than to use such a complicated expression just to fetch a value...

[reply]
[d/l]
[select]
Re: Multidimensional Arrays
by Anonymous Monk on Oct 21, 2008 at 02:15 UTC
    Hi and thanks for the great tutorial...one small note use Data::Dumper; print Dumper \@array; should be... use Data::Dumper; print Dumper \@shapes; Thanks again
[reply]
Re: Multidimensional Arrays
by Anonymous Monk on Oct 14, 2004 at 06:27 UTC
    Apart from having the drop dead looks, you also write very well. Your tutorials gives a good picture of arrays in arrays and the difference between arrays using () and []. Thanks Kasp
[reply]
Re: Multidimensional Arrays
by sapnac (Beadle) on Jul 06, 2005 at 19:16 UTC
    Thanks Charles
    This really well written and clears the concept

    Keep up the good work

    Sapna
[reply]
Re: Multidimensional Arrays
by czyker (Initiate) on Sep 19, 2011 at 18:34 UTC
    Thank you SO much. Finally an explanation that makes sense. This is absolutely outstanding.
[reply]

Back to Tutorials


A Perl hash is similar to an ordinary array, but instead of using integer indexes, a hash uses "keys" that can take on any scalar value. These are usually strings or numbers.

Syntax: instead of the operator, associative arrays use the symbol, and rather than square brackets , as in , hash elements are referenced using curly brackets , as in .

Hashes are one of the most powerful and commonly used features in Perl. A typical use would be to build a hash that contains a "dictionary", with each key being a word in the dictionary, and the corresponding values being the definitions of those words.

A hash containing the sounds various household pets make is below

my%petsounds=("cat"=>"meow","dog"=>"woof","snake"=>"hiss");

'=>' and ',' are actually interchangeable, so the right side could look exactly like an array. This means that you can assign an array to a hash. In such an assignment, each element with an even index (starting from 0) in the array becomes a key in the hash. The following statements create the same hash as the previous one does

my@array=("cat","meow","dog","woof","snake","hiss");my%petsounds=@array;

But the first style is more preferred because it makes the statement more readable.

To access a hash element, use the curly brackets:

printSTDOUT"The cat goes ".$petsounds{"cat"}.".\n";

will print the following to STDOUT

The cat goes meow.

To add a new sound item to a hash

$petsounds{"mouse"}="squeak!";

To overwrite an existing element, just reassign it

$petsounds{"dog"}="arf!";# The dog now goes "arf!"

To remove an item from a hash, use . Setting the value to does not delete the item; using on a key that has been set to will still return true.

delete($petsounds{"cat"});# will remove "cat" from our hash

"Associative Arrays"[edit]

Originally, a "hash" was called an "associative array", but this term is a bit outdated (people just got sick and tired of using seven syllables). Although it isn't intuitive for newcomers to programming, "hash" is now the preferred term. The name is derived from the computer science term, hashtable.

Working with hashes[edit]

Printing hash contents[edit]

If you know PHP, you may have thought by now of some convenient way to print the contents of your array the way does...

useData::Dumper;printDumper(\%hash);

Counting the number of entries in a hash[edit]

To get the size of the hash, simply find the size of the result of the function, by evaluating it in scalar context:

my%hash=('key1'=>1,'key2'=>2);print"Hash has ".keys(%hash)." elements\n";my$num_elements=scalar(keys(%hash));

Hash of Hashes of Hashes[edit]

You can define multidimensional hash array variables. An example may look like this:

#!/usr/bin/perluseData::Dumper;my%a=();$a{1}{"a"}{"A"}="FIRST";$a{1}{"c"}{"B"}="THIRD";$a{1}{"b"}{"C"}="SECOND";foreachmy$k1(sortkeys%a){foreachmy$k2(sortkeys%{$a{$k1}}){foreachmy$k3(sortkeys%{$a{$k1}{$k2}}){print"$k1\t$k2\t$k3\t$a{$k1}{$k2}{$k3}\n";}}}printDumper(\%a);

This code will produce:

1 a A FIRST 1 b C SECOND 1 c B THIRD $VAR1 = { '1' => { 'c' => { 'B' => 'THIRD' }, 'a' => { 'A' => 'FIRST' }, 'b' => { 'C' => 'SECOND' } } };

One thought on “Perl 2d Array Assignment In C

Leave a comment

L'indirizzo email non verrĂ  pubblicato. I campi obbligatori sono contrassegnati *