In the end I was able to do more or less what I had in mind at the beginning. This implementation is recursive (I wanted to mix in both things) but behaves like an iterator using the closure: It uses two queues (one for read filenames and another for directories to be read) but when a directory is read it iterates over itself until a file is found; still, the interface is an iterator.
{ my @fq; # files my @dq; # directories my $currentDir; sub initDir { push @dq, shift; }; sub getNextFile { my $f; if ( $#fq >= 0 ) { $f = pop @fq; } else { if ( $#dq >= 0 ) { my $r; # filename read local *D; $currentDir = pop @dq; opendir(D, $currentDir) || die "$currentDir: $!"; while ( defined( $r = readdir( D ) ) ) { next if $r =~ /^\.{1,3}$/; my $ff = $currentDir . '/' . $r; if ( -d $ff ) { push @dq, $ff; } else { push @fq, $ff; } } closedir D; $f = getNextFile(); } else { $f = undef; } } return $f; } } my $dir = "c:/inetpub"; # execution start here initDir( $dir ); my $f; my $i = 0 ; while ( defined( $f = getNextFile() ) ) { $i++; print "[$i] $f \n"; }
What do you think about it? is there anything fundamentally flawed with this approach?

In reply to Thank you by l3nz
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.