more useful options PerlMonks

### Depth of AoAs

by CharlesClarkson (Curate)
 on Jan 14, 2002 at 10:17 UTC ( #138529=snippet: print w/ replies, xml ) Need Help??

 Description: I have no clue why anyone might need this. I created it while answering a question about multidimensional arrays. It is my first successful recursive sub. ``` sub depth { my \$arr = shift; return 1 unless ref \$\$arr[0] eq 'ARRAY'; return depth( \$\$arr[0] ) + 1; } ``` Call it with a reference to your array of arrays structure print depth( \@array ); Update: Changed the fourth line to indicate the correct sub.
Comment on Depth of AoAs
Replies are listed 'Best First'.
Re: Depth of AoAs
by rob_au (Abbot) on Jan 14, 2002 at 10:33 UTC
There are two small problems with this code - The first is that you have called the subroutine depth yet reference it within the subroutine as dimensions. Has anyone ever told you that recursion is evil? :-)

Also, if the subroutine is called with something other than an array reference, it still returns a count of 1.

Update

This code addresses the issues above and returns the correct reference depth of the array.

```sub depth {
return 0 unless ref \$_[0] eq 'ARRAY';
return depth( \${\$_[0]}[0] ) + 1;
}

Or alternatively, without recursion ...

```sub depth {
my \$array = shift;
my \$count = 0;
while (ref \$array eq 'ARRAY') {
\$array = \${\$array}[0];
++\$count;
}
return \$count;
}

Update

Okay ... So I was curious and went ahead and benchmarked these subroutines and was pleasantly surprised with the result.

```Benchmark: timing 100000 iterations of loop, recursion...
loop:  6 wallclock secs ( 5.30 usr +  0.00 sys =  5.30 CPU) @ 18
+867.92/s (n=100000)
recursion:  6 wallclock secs ( 5.87 usr +  0.00 sys =  5.87 CPU) @ 17
+035.78/s (n=100000)

Re: Depth of AoAs
by merlyn (Sage) on Jan 15, 2002 at 02:50 UTC
Hey, why is that taking so long to run on this?
```my @x;
push @x, \@x;
{evil grin}

Back to Snippets Section

Create A New User
Node Status?
node history
Node Type: snippet [id://138529]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (12)
As of 2015-08-03 16:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?