in reply to Checking for Directories

You can check if a directory exists using -e, and if it's a directory using -d. So you can probably just use the latter:
print "is directory" if -d "/foo/bar";
For your second question:
opendir DH, "/foo/bar" or die $!; my @subdirs = grep -d, readdir DH; closedir DH or die $!;
Sub-directories are in @subdirs.

Umm, embarrassing update: read chip's answer below for why my second answer is broken. So use his code.

Replies are listed 'Best First'.
RE: Re: Checking for Directories
by chip (Curate) on Jul 28, 2000 at 23:31 UTC
    Sorry, btrott, that won't work ... readdir() only returns basenames, and that's not enough for -d to work. Besides, you probably don't want to count '.' and '..'. How about:

    my $dir = '/foo/bar'; opendir DH, $dir or die $!; my @subdirs = grep { -d } map { "$dir/$_" } grep { $_ ne '.' && $_ ne '..' } readdir DH; closedir DH;

        -- Chip Salzenberg, Free-Floating Agent of Chaos

      If the debugger is accurate, you are stepping through the array three times to produce your results. If you have a directory with a large number of files in it, this is not the most runtime-efficient way of doing it.

      This version makes a single pass through the directory listing.

      #Assume all the open code foreach( readdir DH ) { next if ( $_ eq '.' or $_ eq '..' ); push @subdirs, "$dir/$_" if ( -d "$dir/$_" ); }
      Of course, you may still not like this. It will be kinda hungry on memory, especially if the ratio of files to directories is very large - the foreach will suck in every file at once. It may be better to try it with a while loop - it will be easier on memory but will take longer due to buffering issues.
      mikfire
        Unless you've run it under Benchmark, you don't know whether your intuition is correct about which approach is faster. Besides, fewer lines of code and fewer variable names makes for easier maintenance, all things equal.

            -- Chip Salzenberg, Free-Floating Agent of Chaos

      Oops. Thanks for the reminder. My test script was running in the same directory that I was opendir-ing. Stupid, but oh well. :)
RE: Re: Checking for Directories
by steveAZ98 (Monk) on Jul 28, 2000 at 23:31 UTC
    Or you could try something like this.
    my @n = grep { -d $_ } <*>;