I would like to find all the Empty directories from the current directory and delte the same.
Could any one Suggests some Modules to do this task.
Is there a way to find the Empty directory in Perl.
Thanks in advance.
Just remove them. If they're not empty, rmdir will fail. In this case, you don't care that it fails, ignore the error, and keep going.
use File::Find;
finddepth(sub { rmdir $_ if -d }, $some_path);
Update: added 'depth' as per [merlyn]'s correction.
-- Randal L. Schwartz, Perl hacker
Be sure to read my standard disclaimer if this is a reply.
perl -e 'while(<./*>){@a=<$_/*>;rmdir if -d && ! $a[0]}'
Try using the opendir and readdir functions along with a file test. Something like:
opendir (DIR, ".") or die "Cannot open the current directory: $!";
my @files = grep {$_ ne '.' and $_ ne '..'} readdir DIR;
close (DIR) or die "Cannot close the current directory: $!";
foreach my $file (@files) {
if (-d $file) {
opendir (SUBDIR, "$file") or die "Cannot open the sub directory: $!;
my @subfiles = grep {$_ ne '.' and $_ ne '..'} readdir DIR;
closedir(SUBDIR) or die "Cannot close the sub directory: $!";
unless (@subfiles) {
unlink("$file");
}
}
}
I have not actually tried this to be sure it works. Furthermore, it only deletes empty directories in the current directory. You would need to convert it into a recursive subroutine if you wanted to mine further into the directory tree.
#!/usr/bin/perl
use File::Find;
finddepth sub {
return unless -d;
rmdir($_);
}, @ARGV;
See also [id://437881]
Traverse( "./", 1 );
sub Traverse { # returns 0 for empty else 1
my $dir = shift;
my $top = shift; # flag for different treatment of top dir
unless( opendir my $dh, $dir ) {
warn "$!: $dir\n";
$top or return 1;
}
for my $file ( grep !/^\.\.?/, readdir $dh ) {
my $path = "$dir/$file";
if ( -d $path ) {
if ( Traverse( $path, 0 ) ) {
$top or return 1;
}
else {
rmdir $path;
}
}
else {
$top or return 1;
}
}
closedir $dh;
return 0;
}
perlmonks.org content © perlmonks.org and DungeonKeeper, ezekiel, jesuashok, manigandans, merlyn, smokemachine, Tanktalus, zentara
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03