I have started playing around with Perl closures lately following the very good Closure on Closures tutorial by broquaint, and I thought I'd write an iterator to access, one by one, the files recursively contained within a directory path. The problem, when written in a recursive way, is very simple; this is a simple solution (a better solution would avoid returning lists, but this is simple and works):
I was thinking about how to convert this code into an iterator built with closures, but I'm frankly clueless at it. Is it possible, feasible and reasonable? Could you explain me how?use strict; sub recursiveReadDir { my ($dir) = @_; my @res; my $f = ''; my $ff = ''; local (*D); print "Reading: $dir ...\n"; opendir(D, $dir)|| die "can't opendir $dir: $!"; while ( defined( $f = readdir( D ) ) ) { $ff = $dir . '/' . $f; next if $f =~ /^\.{1,3}$/; if ( -d $ff ) { push @res, recursiveRead( $ff ); } else { push @res, $ff; } } closedir D; return @res; } print recursiveRead( "c:/inetpub/wwwroot" );
In reply to Turning a recursive function into an iterator by l3nz
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |