http://qs1969.pair.com?node_id=139960

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

Can you show me how to validate the existence of a directory? If the directory name has a space in between, what should I do? And how to capture all the files under a directory? Thanks much. And God bless all Monks! Lilly

Replies are listed 'Best First'.
Re: Opening a Directory
by FoxtrotUniform (Prior) on Jan 19, 2002 at 01:48 UTC

    Can you show me how to validate the existence of a directory?

    You want the file test operators, specifically -d.

    If the directory name has a space in between, what should I do?

    Nothing special, as long as you have the whole dir name instead of just the first word.

    And how to capture all the files under a directory?

    opendir, readdir, closedir.

    And God bless all Monks!

    Which one?

    --
    :wq
Re: Opening a Directory
by wog (Curate) on Jan 19, 2002 at 01:55 UTC
    If the directory name has a space in between, what should I do?

    If you call out to a shell command using the name of the direcotry use quotes or, better, the multi-argument form of system or exec (update: oops, open doesn't have which accepts an arbitrary number of arugments. If you want to not have spaces or quotes be an issue and to capture the output of or send input to a command use open and exec's multi-argument form.) Otherwise, perl's internal functions (rmdir, mkdir, chmod, etc.) and any modules shouldn't have a problem.

    And how to capture all the files under a directory?

    I'd reccommend File::Find, since that'll do the recursion necessary (into subdirectories, etc.). (But you can use opendir, readdir, and closedir directly, if you really want to.)

Re: Opening a Directory
by jonjacobmoon (Pilgrim) on Jan 19, 2002 at 02:04 UTC
    There are a number of ways to do this, although I cannot say definitely if this will work with a space in a directory. However it should, theoretically still work by doing any of the following:

    #!/usr/bin/perl -w use strict; my @result = map { glob($_) } "*"; foreach (@result) { if (-d "$_") { print "$_ is a directory\n"; } }

    This is directly from the camel book and will return a listing of everything in the current directory. See the camel book for more details on glob.

    You can also use opendir and readdir to get a handle, open the directory, read the directory, test if any files in directory are directories. You might want to take the advice from the camel book on this and use grep to avoid the "." and ".." directories, but it sounds like you are on a non-*nix system so you may not need to worry about it.

    The other way, is to use the File::Find which is well documented both here and at CPAN.

    Hope that helps. Nice to know you have so many choices, huh? Ain't Perl great!


    I admit it, I am Paco.
A reply falls below the community's threshold of quality. You may see it by logging in.