#!/usr/bin/perl
# remove-empty-dirs - remove recursively empty directories
# 2002-2020 Vlado Keselj http://web.cs.dal.ca/~vlado

$| = 1;
&remove_empty_dirs(@ARGV);

sub remove_empty_dirs {
    my $count = 0;
    while ($#_ > -1) {
	   my $dir = shift;
	   # symbolic link
	   if (-l $dir) { next }

	   next if not -e $dir;

	   # file
	   if (not -d $dir) { next }
	   
	   local ($_, *DIR);
	   opendir(DIR, $dir) || die "can't opendir $dir: $!";
	   map { /^\.\.?$/ ? '' : ($count += &remove_empty_dirs("$dir/$_")) } readdir(DIR);
	   closedir(DIR);

	   # is it empty?
	   my $count1 = 0;
	   opendir(DIR, $dir) || die "can't opendir $dir: $!";
	   map { /^\.\.?$/ ? '' : ($count1 += 1) } readdir(DIR);
	   closedir(DIR);
	   if ($count1 == 0) {
	       print "Removing $dir (empty dir)\n";
	       rmdir $dir or die "Error removing $dir: $!";
	       $count += 1;
	   }
       }
    return $count;
}

__END__ # Documentation

=head1 NAME

remove-empty-dirs - remove recursively empty directories

=head1 DESCRIPTION

The command C<remove-empty-dirs> removes recursively all empty directories
that are subdirectories of the directories given in the argument line.

=head1 SYNOPSIS

 $ remove-empty-dirs .

Removes all empty subdirectories recursively of the current directory.

=head1 AUTHOR

Vlado Keselj http://web.cs.dal.ca/~vlado 2002-2020

=head1 LICENSE

Artistic License 1.0 L<perlartistic>

=head1 INSTALLATION

Using C<cpan>:

 $ cpan App::Utils

Manual install:

 $ perl Makefile.PL
 $ make
 $ make install

=cut
