in reply to Thank you
in thread Turning a recursive function into an iterator

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->()));