in reply to Testing for readdir failure

Maybe you could just try this:

my @x; if ( opendir(my $DIR, $somedir) ) { @x = readdir($DIR) or die "$!"; closedir($DIR); }

At least, it would give you a diagnostic if the readdir instruction fails.

Also using the strict and warnings pragmas might help if you don't (and you should do it).

A possible alternative would be to use the glob function, which is often more practical than the opendir/readdir combination. Perhaps something like this:

my @x = glob "$somedir/*.*" if -d $somedir;

would do the trick.

Replies are listed 'Best First'.
Re^2: Testing for readdir failure
by eye (Chaplain) on Apr 21, 2013 at 12:14 UTC
    From the documentation, it is not clear that readdir returns an error in $!.

    Another approach would be to stat the directory and verify that the link count matches the number of file names returned. That seems likely to catch an error, though not to identify the cause.

      > From the documentation, it is not clear that readdir returns an error in $!.

      Worse! in my tests it returns sometimes "File exists" if there's no error.

      see Testing for readdir failure

      Cheers Rolf

      ( addicted to the Perl Programming Language)

      Well it does seem to populate $! in at least some cases. I have an empty directory called "foo":

      $ perl -e 'opendir DIR, "foo" or die "$!"; @c=readdir DIR; print "@c\n +"; closedir DIR; @c=readdir DIR or die "$!"' . .. Bad file descriptor at -e line 1.

      I also got the following $! error in my quick tests under the debugger:

      DB<8> @c = readdir DIR or die "$!" Illegal seek at (eval 12)[/usr/lib/perl5/5.10/perl5db.pl:638] line 2.