Schemer
Schemer

Reputation: 1675

Perl finding names of directories and files but determining they do not exist

No matter what directory I use for TARGET, this Perl code correctly finds the name of every subdirectory and file in TARGET but then determines that none of them exist except for "." and "..".

my $source_dir = "C:\\path to directory\\TARGET;

opendir(my $DIR, $source_dir) || die $!;
while (my $file = readdir($DIR))
{
    my $file_exists = (-e $file ? "exists" : "does not exist");
    print("$file $file_exists\n");
}

Output:

. exists
.. exists
FILE does not exist # where FILE is the name of every other subdirectory or file in TARGET

What's truly baffling me is that if I change TARGET to one of it's subdirectories, the script successfully navigates to the subdirectory -- having previously determined that it does not exist -- and then produces the same output in the new subdirectory.

Any advice is appreciated.

Upvotes: 2

Views: 74

Answers (2)

clt60
clt60

Reputation: 63952

You can also use some modules, what allows you many additional easying functions, my favorite is Path::Tiny. E.g.:

use 5.010;
use warnings;
use Path::Tiny;

$iter = path("C://Users/jm")->iterator;

while ( $path = $iter->() ) {
    say "$path";
}

The iterator automatically skips the . and the .., you can add option to recurse into subdirs and so on...

Upvotes: 2

darch
darch

Reputation: 4311

readdir only returns the filename, not the whole path. Consequently, -e $file looks for $file in the current working directory, not in $source_dir. Every directory contains entries named . and .., so those get found. But none of the other files in the working directory have the same name as files in $source_dir, so they don't get found when -e goes looking for them.

So you need to combine $source_dir and $file:

use File::Spec::Functions qw/catfile/;

my $full_path = catfile($source_dir, $file);
my $file_exists = (-e $full_path ? "exists" : "does not exist");
print("$file $file_exists\n");

Upvotes: 3

Related Questions