For this I'll refer to a previous node
349582 and especially
tye's response to that node
350948 in which he describes a "next" method iterator.
I've since used the guts of this "next" method (Big Thanks to
tye) in a module I'm writing. I'm wanting to amend that method so that you can specify it to only go so deep into the directory tree. Here is the code:
sub this_deep {
my ($self, $depth) = @_;
$depth = -1 unless @_ > 1;
$self->{depth} = $depth;
}
sub next {
my $self = shift;
while( 1 ) {
if ( @{ $self->{output} } ) {
my $line = shift @{ $self->{output} };
return $line;
}
if ( ! @{ $self->{dirs} } ) {
return;
}
my $dir = shift @{ $self->{dirs} };
if (-d $dir) {
if( opendir( DIR, $dir ) ) {
map {
my $file = $_;
my $fullfile = File::Spec->catfile( $dir, $file );
if (-d $fullfile && ($self->{level} <= $self->{dep
+th} || $self->{depth} == -1)) {
push (@{ $self->{dirs} }, $fullfile);
}
} File::Spec->no_upwards( readdir(DIR) );
closedir DIR;
} else {
warn "\a\a\aopendir FAILED, $dir: $!";
}
} else {
warn "\a\a\aNOT A DIRECTORY: $dir\n";
}
}
}
As you can see in this code I've put in the checks for the $self->{level} in that it will only push to the $self->{dirs} stack if the current level is below the specified depth or depth == -1 (if depth is set to -1 it will fully recurse the directory tree)
I'm having trouble building into this how to track the depth to ensure it only goes as far as specified. Any suggestions?
Update: I should add that what makes this tricky is the code makes it go DOWN a directory tree first before starting on the next level, not across the directory tree as is usually the case.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.