Detect empty directory with Perl

情到浓时终转凉″ 提交于 2019-12-17 19:19:11

问题


What is an easy way to test if a folder is empty in perl? -s, and -z are not working.

Example:

#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"; 
}

These above, do not work properly to tell me that the folder is empty. Thanks!


Thanks all! I ended up using:

sub is_folder_empty { my $dirname = shift; opendir(my $dh, $dirname) or die "Not a directory"; 
return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0; }

回答1:


A little verbose for clarity, but:

sub is_folder_empty {
    my $dirname = shift;
    opendir(my $dh, $dirname) or die "Not a directory";
    return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0;
}

Then you can do:

if (is_folder_empty($your_dir)) {
    ....
}



回答2:


Using grep { ! /^[.][.]?\z/ } readdir $dir_h can be problematic for performance in case the check is done many times and some directories may have many files.

It would be better to short-circuit the moment a directory entry other than . or .. is found.

On Windows XP with ActiveState perl 5.10.1, the following sub seems to be twice as fast as the grep approach on my $HOME with 100 entries:

sub is_dir_empty {
    my ($dir) = @_;

    opendir my $h, $dir
        or die "Cannot open directory: '$dir': $!";

    while ( defined (my $entry = readdir $h) ) {
        return unless $entry =~ /^[.][.]?\z/;
    }

    return 1;
}



回答3:


Or without any grepping or regular expressions - which rules out any chance of weird file names accidentally getting though. Plus slightly faster is my testing.

#!/usr/bin/perl
use strict;
use warnings;

sub is_dir_empty {
    return -1 if not -e $_[0];   # does not exist
    return -2 if not -d $_[0];   # in not a directory
    opendir my $dir, $_[0] or    # likely a permissions issue
        die "Can't opendir '".$_[0]."', because: $!\n";
    readdir $dir;
    readdir $dir;
    return 0 if( readdir $dir ); # 3rd times a charm
    return 1;
}

my @folders = qw( ./ ./empty ./hasonefile ./hastwofiles ./doesnotexist ./afile );
for my $folder ( @folders ) {
    print "Folder '$folder' ";
    my $rc = is_dir_empty( $folder );
    if( $rc == -1 ) {
        print "does not exist\n";
    } elsif( $rc == -2 ) {
        print "is not a directory\n";
    } elsif( !$rc ) {
        print "is not empty\n";
    } else {
        print "is empty\n";
    }
}

Pretty simple. If you get three valid responses from a call to readdir, then you know there must be a file in there. Regardless of what name the file may have - or the order in which the files are being processed. Would have preferred something called 'is_dir_used' as I personally don't like the double-negative function name and return value.




回答4:


There is also File::List from cpan. It's overkill here, but can be handy for slightly more complex requests like test if a directory is empty with the meaning it contains only empty directories (ie: not files).




回答5:


opendir(DIR,"DIR PATH") or die "Unable to open directory \"DIR PATH\" \n";
my @drList = readdir(DIR);
close(DIR);
if( grep(/\w/,@drList) ){ print "Not Empty\n" }
else { print "Empty\n" }



回答6:


  sub is_folder_empty {
        my $dirname = shift;
        my @files = File::Find::Rule->file()->name('*')->maxdepth(1)->in("$dirname");
        return $#files < 0;
    }



回答7:


Credit to DevShed

if (scalar <directory/*>) {print qq|File Exists\n|}

Edit

To include hidden files:

@arr = <directory/* directory/.*>;
@arr = grep {!/^directory/[.]{1,2}$/} @arr;
if (@arr) { print qq|File or Directory Exists\n| }

Please read the comments as there have been good points made. Despite the negative points this answer has received, it is still correct.



来源:https://stackoverflow.com/questions/4493482/detect-empty-directory-with-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!