Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am using File::Find.
How do I check if the directory being used for the File::Find input is a valid and existing directory? This isnt working below:
use File::Find; my $dir = '\TestDir'; if(-d "$dir") #also tried: if(-d $dir) { find( \&SubRoutineHere, $dir); } else { print "No such directory\n"; }

Replies are listed 'Best First'.
Re: Checking for valid directory
by gjb (Vicar) on Jul 03, 2003 at 15:23 UTC

    You may want to check whether it exists (-e), can be read (-r) and that you can cd into it (-x) apart from the check you're already doing. I'd do the -e first for obvious reasons ;-)

    See the docs for more details.

    Hope this helps, -gjb-

Re: Checking for valid directory
by tcf22 (Priest) on Jul 03, 2003 at 15:23 UTC
    What exactly isn't working? I tried this with a good directory and a non-existent directory and it worked correctly in detecting the existence of the directory. Couldn't tell you whether or not it is a problem in your sub, because there is no code provided.
    Are you sure that you have permission to read the directory. Maybe you should check that as well.
Re: Checking for valid directory
by cbro (Pilgrim) on Jul 03, 2003 at 15:24 UTC
    I'm not sure why you have the single backslash in your directory name, but if you are using Windows then you need to escape the slash, (e.g. my $dir = "\\TestDir";).

    Either way, don't use backslashes. This way you don't have to worry about escaping them. Here's an example (I'm assuming your using windows because of your $dir definition):
    my $dir = "c:/docume~1/chris/TestDir"; if (-d $dir) { print "It Exists"; } else { print "Does Not Exist"; }

    So, the first method you tried...the one w/out $dir in quotes should have worked. Try making $dir an absolute path, and use forward slashes. See if that makes a difference.
    HTH,
    Chris
      Sorry folks, I had the output going to stderr so that is why I didnt see the output. Again, sorry to not catch this before I posted!