in reply to Re: Quickest way to get a list of all folders in a directory
in thread Quickest way to get a list of all folders in a directory

You also have to test that what you're getting are really dirs.

No. opendir already does that. Checking it explicitly is redundant at best, and adds a race condition at worse.

Isolate your directory path value

That's a great idea since it allows you to print it in the error message, something you failed to do. This would have been extremely useful to the OP.

$ perl -e' my ($dir_qn) = @ARGV; opendir(my $dh, $dir_qn) or die "Can'\''t open dir $dir_qn: $!\n"; ' somefile Can't open dir somefile: Not a directory

Replies are listed 'Best First'.
Re^3: Quickest way to get a list of all folders in a directory
by leocharre (Priest) on Aug 13, 2009 at 15:06 UTC

    Yes- I was thinking here about the person reading the code more than the code- it would make it extra special with sugar on top obvious about what the problem is or is not.. And.. if the OP is not even checking that the entries are files or dirs or what- then seeing a line that tells -d or x.. might be needed? For the human, that is.

    But you're right, very good point, opendir() already checks that it's a dir.

      I was thinking here about the person reading the code more than the code

      Maybe it's just me, but I think the person also doesn't need a -d check in addition to opendir to know a directory is being opened.

        Well..

        We know that opendir(DIR,'/tmp/mydir') won't work if it's not a directory. We also know that it won't work if the permissions do not allow it.

        If we say -d '/tmp/mydir' or die('/tmp/mydir is not a directory'), then to the novice- this is like the code staring at them in the face telling them.. Yes, after this, you can rest assured, the directory is there, the string can indeed be interpreted as a path.

        I think this is useful. To someone who: would call readdir() to get a list of directory entries in a directory- thinking that the list will only contain directories, excempting files, fifos, etc.

        Yes, it is redundant. Yes, it's poor practice. I'm throwing it out there that it could be of use to someone getting their rationale around what's going wrong.
        And yes, of course- the person does not *need* a -d check in addition to opendir.
        Maybe some are too experienced to appreciate the pains and horrors of a novice learning anew? :-) Or maybe RTFM applies here. Also valid. Maybe my suggestion is too lenient and just opens up more holes than it patches, too.