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)

 

And the code used for the benchmarking ...

#!/usr/bin/perl use Benchmark; use strict; timethese (100000, { 'recursion' => q! sub depth { return 0 unless ref $_[0] eq 'ARRAY'; return depth( ${$_[0]}[0] ) + 1; }; my $array = [ [ [ 1 ], [ 1 ] ], [ [ 1 ], [ 1 ] ]]; my $result = depth($array); !, 'loop' => q! sub depth { my $array = shift; my $count = 0; while (ref $array eq 'ARRAY') { $array = ${$array}[0]; ++$count; } return $count; } my $array = [ [ [ 1 ], [ 1 ] ], [ [ 1 ], [ 1 ] ]]; my $result = depth($array); ! });
perl -e 's&&rob@cowsnet.com.au&&&split/[@.]/&&s&.com.&_&&&print'

In reply to Re: Depth of AoAs by rob_au
in thread Depth of AoAs by CharlesClarkson

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.