Shawn H Corey <shawnhco...@gmail.com> writes:

 Harry Putnam wrote:
>> Is there a simple test to determine if a directory is empty or not?
>> 
>> Or do you have to opendir, readdir, or something similar with a full
>> block.
>> 
>> 
>
> That depends on what you mean by empty.  On Linux, even empty
> directories have . and ..

No actual files

> Why do you want to test for this?  If all you want to do is remove
> directories, use rmtree() from File::Path.  It will remove the
> directory, all its files and sub-directories.

I'm writing a script that searches files under a hierarchy for
specific regex.

If the regex is found, these files are then symlinked into another
directory.

I want to know if the receiving directory is empty of actual files.
Since if it is not; then first the user must be asked if she wants to
continue, if so, then a subfunction must be employed to ensure nothing
is clobbered.

The subfunction  compares incoming filenames to any filenames
present in the receiving directory and adds a numeric extension if
there are any matches; to guarantee a unique filename.
That code is a little more involved since some of the filenames present
may well already have extensions 

But all I'm asking here is for the easiest way to see if the receiving
directory is empty.

The code I've devised seems pretty clunky (I haven't tested the script
yet since I'm writing several other parts right now, so not even sure
it works).  

I suspected that `find' would find at least (.) and possibly (..) like
long `ls -l' does... what I saw is that it finds only (.) if the dir
is empty.

So I was asking how to do that test in case there is a better way.
-------        ---------       ---=---       ---------      -------- 
  [...]
  
  use strict;
  use warnings;
  use FIle::Find;
  
  [...]

  my @dircontent;
  find(
    sub {
      ## Collect anything that is not a single dot (.) 
      ## For later comparision to files found in search
      if(! /^\.$/) {push @dircontent , $_;
      }
    }, $def_dir
  );

  ## if `dircontent' is 0, it means only (.) was found and we
  ## can skip this
  if(@dircontent > 0){
    print "  Default directory <$def_dir> is not empty
    if we proceed, any clashing filenames will be re-written
    adding a numeric extension to make the name uniq so nothing
    gets overwritten.
    proceed [y/n] > ";
  
    my $ans = <STDIN>;
    if ($ans !~ /^y$/){
      print "Aborting by user request . . .\n";
      exit;
    }
  }
  [...]


-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to