I want to find all of a certain type of file in a directory tree (in this case JPEGs) and simply print them. My problem is the recursion through the tree. Here is what I am using:
my $root_dir = '/top/directory/to/start/search'; RunDirs($root_dir); sub RunDirs { my $dir = shift; opendir(TMP_D,"$dir") or die "$! opening $dir"; while(my $tmp = readdir(TMP_D)) { $tmp = "$dir/$tmp"; if ($tmp =~ /\.\.?/) { next; } if (-d $tmp) { RunDirs("$tmp"); } elsif ($tmp =~ /^(\w*)\.(jpg|jpeg)$/) { print "$tmp\n"; } } closedir(TMP_D); }
It works, but it only goes through the first branch, and then stops...for example, say this was a directory structure of mine that I was searching:
-| ROOT -|-| SUB 1 -|-|-| SUB 1.1 -|-|-|-| SUB 1.1.1 -|-|-|-|-| SUB 1.1.1.1 -|-|-|-|-| SUB 1.1.1.2 -|-|-| SUB 2.1 -|-| SUB 2 -|-|-| SUB 2.1 -|-|-| SUB 2.2
The program would only search through the first tree it hits, then stop. In the above example, it would search this and stop:
ROOT -> SUB 1 -> SUB 1.1 -> SUB 1.1.1 -> SUB 1.1.1.1
but it would never get to SUB 1.1.1.2 or SUB 2.1 or SUB 2 or anything, it just stops. I thought that after it had hit the bottom of a certain tree, it would start going back up naturally because of the recursion I used (calling RunDirs multiple times) because the instances of RunDirs() for the higher directories would still be open, and therefore would just grab another entry from readdir(). But obviously, this isn't that is happening? What am I doing wrong - I didn't think directory searching was very difficult, but I guess I am doing something wrong!

Thanks for all the help!
R.Joseph

In reply to Procesing directories by r.joseph

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.