in reply to Re: Checking for Directories
in thread Checking for Directories

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

Replies are listed 'Best First'.
RE: RE: Re: Checking for Directories
by mikfire (Deacon) on Jul 28, 2000 at 23:50 UTC
    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

RE: RE: Re: Checking for Directories
by btrott (Parson) on Jul 28, 2000 at 23:48 UTC
    Oops. Thanks for the reminder. My test script was running in the same directory that I was opendir-ing. Stupid, but oh well. :)