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

Dear Monks,
Why in this case if( -d $_ ) does not detect a directory
opendir(DIR, $mydir); my @files = readdir(DIR); closedir(DIR); foreach (@files) { next if( -d $_ );
And when I indicate $mydir."/$_" it does ?
opendir(DIR, $mydir); my @files = readdir(DIR); closedir(DIR); foreach (@files) { next if( -d $mydir."/$_" );

Replies are listed 'Best First'.
Re: if ( -d ) question
by kennethk (Abbot) on Mar 15, 2011 at 15:48 UTC
    As it specifies in -X, -d and its brethren act relative to the current working directory. If $mydir is not ".", then you have the wrong file list. By specifying $mydir."/$_" (or "$mydir/$_"), you are giving a full path. You can also swap your current working directory with chdir, but that may have side effects you are not expecting.
Re: if ( -d ) question
by Corion (Patriarch) on Mar 15, 2011 at 15:45 UTC

    Because "$_" and "$mydir/$_" are two different things?

    It's unclear to me what different outcome you expect. Should -d "foo" be true if anywhere on the filesystem there exists a directory with a name of "foo"?

Re: if ( -d ) question
by Anonymous Monk on Mar 15, 2011 at 18:08 UTC
    It is always a wise idea to create a fully-qualified file name for use in all such tests.   There are portable CPAN modules that can help you with doing that.   When you are testing to see if a thing exists, it is critical that you are precisely sure what (Perl thinks...) you are actually looking for.   It is terribly easy to destroy a priceless Ming vase...