In Perl, strictly speaking, arrays are only ever one dimensional and only ever contain scalar values. However, a reference to something, including array and hash somethings, is scalar, so a single dimensional array may contain elements that are references to other single dimensional arrays. Voila - two dimensional arrays.

For the full skinny see perllol, but to get you started you could create your array by one of:

my @array1 = (['a', 'b'], ['c', 'd']); my @ab = qw(a b); my @cd = qw(c d); my @array2 = (\@ab, \@cd); my @array3; push @array3, \@ab; push @array3, \@cd; my @array4; push @array4, (\@ab, \@cd);

or numerous variations on the theme. To access an element in the array you can:

print "$array1[0][0]\n\n"; for (my $x = 0; $x < @array1; ++$x) { for (my $y = 0; $y < @{$array1[$x]}; ++$y) { print "$array1[$x][$y] "; } print "\n"; } print "\n"; print "@$_\n" for @array1;

which prints:

a a b c d a b c d

Perl is environmentally friendly - it saves trees

In reply to Re: Creating two dimensional array and adding elements to it by GrandFather
in thread Creating two dimensional array and adding elements to it by Anonymous Monk

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.