Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to create a two dimensioanl array and add values to it.
push(@temp, a , b); I also tried with getting the values into two 1 dimensional arrays and + putting them in one using @temp = (\@arraya, \@arrayb); does not seem to be working. both the arrays are same size. I want val +ues in the following way... a b c d

Replies are listed 'Best First'.
Re: Creating two dimensional array and adding elements to it
by ikegami (Patriarch) on Feb 25, 2008 at 19:40 UTC

    There isn't truly such a thing as a 2d array in Perl. Just arrays of array references.

    What you do is create an array, and push a reference to it.

    my @a; push @a, [ 'a', 'b' ]; push @a, [ 'c', 'd' ]; for my $row (@a) { for my $cell (@$row) { print("$cell "); } print("\n"); }

    Update: Or with named arrays:

    my @a; push @a, \@arraya; push @a, \@arrayb;
Re: Creating two dimensional array and adding elements to it
by GrandFather (Saint) on Feb 25, 2008 at 19:41 UTC

    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