To me, recursion means "let the programming language manage the stack", so the use of either an explicit stack or queue bothers me when I'm trying to do things recursive-like.

So here's a somewhat more fully iterator-style solution that uses the dirhandle as an iterator, and keeps a single scalar as the memory between invocations. Oh, and this isn't totally necessary, but I convert simple files to iterators that return the file once. I'm doing that because whenever I write iterators, I always use pretty much the same pattern: compute the next value if needed, consume a result from a sub-iterator, then return it. This allows a class hierarchy of iterators that override only the minimum necessary operations. Anyway, here's the code:

use IO::Dir; sub make_reader2 { my ($dirname) = @_; my $d = new IO::Dir $dirname or die "opendir $dirname: $!"; my $next; return sub { while (1) { unless (defined $next) { my $entry = $d->read or return; next if $entry eq '.'; next if $entry eq '..'; $entry = "$dirname/$entry"; if (-d $entry) { $next = make_reader2($entry); } else { $next = sub { my $r = $entry; undef $entry; $r; }; } } my $result = $next->(); return $result if defined $result; undef $next; } }; } my $reader = make_reader2($ARGV[0]); print "$_\n" while (defined($_ = $reader->()));

In reply to Re: Thank you by sfink
in thread Turning a recursive function into an iterator by l3nz

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.