title: Detect empty directory with Perl
body: <p>What is an easy way to test if a folder is empty in perl? -s, and -z are not working.</p>
  
  <p>Example:</p>
  
  <pre><code>#Ensure Apps directory exists on the test PC.
  if ( ! -s $gAppsDir )
  { 
      die "\n$gAppsDir is not accessible or does not exist.\n"; 
  }
  
  #Ensure Apps directory exists on the test PC.
  if ( ! -z $gAppsDir )
  { 
      die "\n$gAppsDir is not accessible or does not exist.\n"; 
  }
  </code></pre>
  
  <p>These above, do not work properly to tell me that the folder is empty. Thanks!</p>
  
  <hr>
  
  <p>Thanks all! I ended up using:</p>
  
  <pre><code>sub is_folder_empty { my $dirname = shift; opendir(my $dh, $dirname) or die "Not a directory"; 
  return scalar(grep { $_ ne "." &amp;&amp; $_ ne ".." } readdir($dh)) == 0; }
  </code></pre>