Several of the functional languages have gone to some effort to have the compiler recognize when recursion can be done by a loop instead. Perl does not. However recognizing that for yourself can be useful. When you can do it it is generally faster, more flexible, etc.

The following code is a native Perl version of what is already done by the UNIVERSAL::isa() method. It is a method that tells whether one class inherits from another. I have implemented this search of a tree-like inheritance structure without recursion by using an array as a stack. (As opposed to having a stack of function calls.)

Try to write a recursive version of the same. Don't forget the pruning of packages that you have already seen in this call to the method (in case there is a circular inheritance path!), and the inclusion of the special case of UNIVERSAL that everything inherits from.

Note that strict 'refs' are turned off. This is the only construct that I have seen where I did not think doing this was a mistake, trying to access a global in your caller's package.

sub isa { my $obj = shift; my $base = ref($obj) || $obj; my $class = shift; my %is_seen; my @pkgs = ("UNIVERSAL", $base); no strict 'refs'; while (scalar @pkgs) { my $pkg = pop @pkgs; return 1 if ($pkg eq $class); # Found it! next if exists $is_seen{$pkg}; # Already processed this one ++$is_seen{$pkg}; # Mark this package seen push @pkgs, @{"${pkg}::ISA"}; # Append what this inherits f +rom } # Searched the inheritance tree, failed to find it, so... return 0; }

In reply to Loops instead of recursion by tilly

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.