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

So what am I doing wrong here? If I have the current directory set to C: in the command prompt and run this code I get varried results as to what directories are returned. The only way that I can get correct dirs returned is if I have the command prompt at the directory that I am trying to search. Is this the way that is has to be done. I have seen other methods but because I am trying to learn I would like to know why this method is flawed?
opendir dirs2, "D:" or die "Couldn't open directory: $!"; while ($_ = (readdir dirs2)) { if (-d $_) { print "Directory: $_\n"; } }

edited: Mon Sep 22 21:10:49 2003 by jeffa - code tags

Replies are listed 'Best First'.
Re: Directory path and -d??
by Paladin (Vicar) on Sep 22, 2003 at 21:12 UTC
    readdir only returns the filenames, not the full path, so you either have to chdir to the dir you are working with, or prepend the full path to the filename before using it. ie:
    my $dir = 'D:'; opendir dirs2, $dir or die "Couldn't open directory: $!"; while ($_ = (readdir dirs2)) { if (-d "$dir/$_") { print "Directory: $_\n"; } }
Re: Directory path and -d??
by bart (Canon) on Sep 22, 2003 at 21:35 UTC

    For a start, let us drop the -d test, in order to see things... See also Paladin's reply. But, there's still more going on.

    Windows (and DOS) is a bit strange with regards to directories and drives: each drive has its own internal current directory. You can see it at the DOS prompt too: type cd d:\files for whatever directory that exists there, if your currently on drive C: you'll still see the path on C: as a prompt. You need to type D: to change that.

    Run your script from that prompt, with C: as your current drive, and you'll see different files listed for every directory you chdir'ed to. Really.

    In other Windows languages, you need to use a separate function call to change the current drive, and the current directory on a drive.

    You commonly don't notice anything in Perl, because chdir (and Cwd's cwd) changes/report both drive and directory at once.

    Conclusing: even in Perl, don't use "d:"; use a full path, like "d:\\" or "d:/", "d:\\files" or "d:/files".

      I have now discovered the creation of paths but thanks for confirming this for me. I am not using File::Find as I have made my code work and am now using one of the prefered ways. I have learned allot about the syntax by just doing these simple tests.

      Thanks for all the help
      Paul Neale

Re: Directory path and -d??
by tcf22 (Priest) on Sep 22, 2003 at 21:24 UTC
    You could also try the glob() function.
    foreach(glob('d:\*')){ if(-d $_){ print "Directory: $_\n"; } }

    - Tom