This is the sort of situation that'd be perfect for coroutines, but we'll have to wait 'til perl6 for native support of that. In the mean time you need to unroll your recursion, which involves building a stack to iterate over e.g
use strict; use File::Spec::Functions 'catfile'; use IO::Dir; sub _dircnts { my $dir = shift; my $do = IO::Dir->new($dir) or die "Couldn't open '$dir': $!"; return map catfile($dir, $_), grep !/^\.\.?$/, $do->read; } sub rec_readdir { my $dir = shift; my @cnts = _dircnts $dir; my $iter; $iter = sub { my $f = pop @cnts; return unless defined $f; push @cnts, _dircnts $f and return &$iter if -d $f; return $f; }; return $iter; } my $di = rec_readdir(shift); while(my $file = &$di) { # do stuff here }
That basically builds up a listing of a given directory and pushes it on a stack, the stack is then iterated through and if a directory is found then its contents are pushed on the stack and so on.

Although if you're actually iteratively walking a directory tree then File::Find::Rule will do a much more reliable job (as it in turn uses File::Find) and is oh-so useful :)

HTH

_________
broquaint


In reply to Re: Turning a recursive function into an iterator by broquaint
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.