in reply to Empty directory

Wow you guys are painful. Why all this grepping and loading an entire directory when all we need to do is something like:
sub AreThereFiles { opendir DIR, "/path/to/nowhere" or die "That will linger: $!\n"; while ( $foo = readir DIR ) { chomp $foo; next if ( $foo =~ s/^\.\.?$/ ); closedir DIR; return 1; } closedir DIR; return 0; }
By the very act of reading something other than . or .., we imply the existence of files in that directory. If there are no files, we fall through the loop and return 0.

This method will be a little slower than slurping it all into an array. But, if your directories look like some of my user's it may not actually be all that slower and the memory savings will be worth it.

Yes, the closedir calls are likely redundant but I have been bitten a few too many times while recursing directories and I tend to include them from sheer paranoia.

Mik
Mik Firestone ( perlus bigotus maximus )

Replies are listed 'Best First'.
RE: RE: Empty directory
by chromatic (Archbishop) on May 16, 2000 at 04:19 UTC
    Let's make that compile :) and not return true if there are only directories:
    sub AreThereFiles { opendir DIR, "/path/to/nowhere" or die "That will linger: $!\n"; while (my $foo = readir DIR ) { chomp $foo; next if ( $foo =~ m/^\.\.?$/ ); next unless (-f $foo); closedir DIR; return 1; } closedir DIR; return 0; }
    I put the -X test in there because the original poster mentioned looking for files. If the existence of a sub-directory is appropriate, you can leave it out.
      Some further nitpicking:
      • It's still readdir not readir :)
      • The chomp is not needed
      • Using $_ instead of my $foo would make things cleaner, i.e.
        next if /^\.\.?$/ or ! -f;
RE: RE: Empty directory
by mdillon (Priest) on May 15, 2000 at 22:19 UTC
    thanks for pointing out the benefit of minimal resource usage. and you didn't even have any useless uses of scalar (although i think you could safely lose the 'chomp').