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

My question is simply this,   How do I do a foreach on a multi-dimensional array   My array is 2 dimensional ($array[x][y])   How would I foreach through that?   Thanks!

janitored by ybiC: Minor format cleanup, including balanced <code> tags arounc example snippet

Replies are listed 'Best First'.
Re: Multi-Dimensional Array
by TedPride (Priest) on Jul 03, 2005 at 19:47 UTC
    my @arr = ([1,2],[3,4]); for (@arr) { for (@$_) { print "$_\n"; } }
    EDIT: Or if you want to keep track of where you are:
    use strict; use warnings; my ($x, $y); my @arr = ([1,2],[3,4]); for $x (0..$#arr) { for $y (0..$#{$arr[$x]}) { print "\$arr[$x][$y] = $arr[$x][$y]\n"; } }
      That worked! Perfect thank you
Re: Multi-Dimensional Array
by Fang (Pilgrim) on Jul 03, 2005 at 19:50 UTC
    for my $x (@foo) { for my $y (@$x) { # do your stuff with $y } }

    Update: Check node 30275 as well