in reply to Bad file descriptor error

you are closing the dirhandle IN the loop instead of after it. Just move the 'closedir' line after the following '}'

This is an example why it is better to use well-tested library code instead of redoing the same tasks over and over again. Take a look at File::Find, it might make your task easier next time.

Replies are listed 'Best First'.
Re^2: Bad file descriptor error
by cdarke (Prior) on Mar 22, 2010 at 10:59 UTC
    It is also an example where consistent indentation would have helped to spot the problem, as well as wider indentation of 4 spaces instead of 2 and comments:
    sub getdir { my $dir = shift; # Open the directory handle, reporting the reason ($!) opendir (my $dh, $dir) || die qq(Cannot opendir: $dir: $!); while( my $file = readdir($dh)) { next if ($file =~ m[^\.{1,2}$]); # Ignore . and .. my $path = $dir .'/'. $file; if (-e $path) { # do some stuff } elsif (-d $path) { getdir($path); } closedir ($dh); # Close the directory handle - OOPS } }
      The 4 spaces look much better.

      But the comments you proposed don't add anything of value. "open the directory handle ..." is as easy or difficult to understand as "opendir(...) or ...". Even more obvious with the closedir line, the comment is just redundant noise.

      Comments should add information not repeat it IMHO. A good place for comments is at the start of a subroutine, to exactly specify what parameters are expected and what is returned. Or at really complicated lines to sum up what is done there

        Thank you, everyone.

        I supose the misplacement of the closedir statement was also due to the late hour and lack of sleep, but proper indentation could have avoided that ID10T error.
        File::Find was a godsend in this case. Thank you for the advice.