title: Recursive directory traversal in Perl
body: <p>I'm trying to write a script that prints out the file structure starting at the folder the script is located in. The script works fine without the recursive call but with that call it prints the contents of the first folder and crashes with the following message: closedir() attempted on invalid dirhandle DIR at printFiles.pl line 24. The folders are printed and the execution reaches the last line but why isn't the recursive call done? And how should I solve this instead? </p>
  
  <pre><code> #!/usr/bin/perl -w
  
  printDir(".");
  sub printDir{
  opendir(DIR, $_[0]);
  local(@files);
  local(@dirs);
   (@files) = readdir(DIR);
   foreach $file (@files) {
      if (-f $file) {
        print $file . "\n";
      }
      if (-d $file &amp;&amp; $file ne "." &amp;&amp; $file ne "..") {
        push(@dirs, $file);
      }
   } 
   foreach $dir (@dirs) {
     print "\n";
     print $dir . "\n";
     printDir($dir);
   }
   closedir(DIR);
  }
  </code></pre>