--- Chris Rogers <[EMAIL PROTECTED]> wrote: > Hi all, Hi, Chris. =o) Suggestion below problem description.
> I backed myself into a corner and cold use a little help. I have a > multi-dimensional array that has a know number of elements at the > deepest level but the number of levels is unknown. Here is a brief > example: > $menuarray[5][0] = "5" > . . . . > $menuarray[7][1][1] = "Home" > . . . . > $menuarray[7][5][5][2] = "" > . . . . > $menuarray[7][5][3][1][3] = "20" > . . . . > I need to be able to iterate over the entire array in order so > that the sublevels are shown immediately after the preceding > level. I know there must be a simple way of doing this but I > just can't seem to make it work. I do know how to do: > for $x(0..$#menuarray) { > for $y(0..$#{$menuarray[$x]}) { > ..... > } > } > But that isn't going to work since I don't know how deep the > array goes and that the number of sub levels may differ from > one element to the next. Any help or hints will be greatly > appreciated. Ok, the first thing is to abstract enough that structure doesn't hamstring you. That makes to code harder to get your brain around and harder to read, so make sure you code neatly and document. The trick here is that Perl doesn't really support multidimensional arrays in the way that we think of it doing. It supports one-dimensional arrays of scalars, and those scalars may be references to other, anonymous one-dimensional arrays. If you have a "multidimensional array" and you test the value of a top level cell, you'll find it's a reference. That means that if at any time you find a reference in a cell, there's another level of depth you have to walk. Accordingly, the first solution that comes off the top of my head would be to abstract the code out to a recursive function. sub dive { my @ray = @{$_[0]}; # $_[0] is an array reference. for my $elem(@ray) { # $elem and @ray are instance-local if (ref($elem)) { # if this element is also a ref, dive($elem); # process the next layer; } else { # otherise it's bottom-level data, do_stuff($elem); # so process the actual data } } } Now it doesn't matter what the depth is, because it'll walk the tree. Recode it to use indexes if that's what you need (as in your example), etc., and watch the logic to make sure do_stuff() doesn't get confused by the recursion of dive() calling it from different depths. As always, please sanity check me on this, fellows. Hope that moves you along in the right direction, Chris. Good luck. Paul __________________________________________________ Do you Yahoo!? U2 on LAUNCH - Exclusive greatest hits videos http://launch.yahoo.com/u2 -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]