On Jun 27, 1:52 pm, [EMAIL PROTECTED] (Paul Lalli) wrote:
> On Jun 26, 5:50 pm, [EMAIL PROTECTED] (Leonid L) wrote:
>
> > Many of the proposed solutions I've found on Google do not work for
> > me, perhaps because they assume Unix/Linux host.
>
> Or, perhaps because you're doing something wrong?   How about posting
> one of these methods that "don't work", so we can evaluate for
> ourselves?
>
> >  I need a sub that
> > will reliably tell me whether a given directory isempty(I am running
> > Perl on Win XP, NTFS file system). Please give your implementation a
> > quick test on a similar platform before posting.
>
> There's a couple hundred ways.  Here's two:
>
> #!/usr/bin/perl
> use strict;
> use warnings;
>
> mkdir("working_dir") or die "Cannot create working_dir: $!";
> chdir("working_dir") or die "Cannot change to working_dir: $!";
>
> mkdir("empty") or die "Can't createempty: $!";
> mkdir("subdir") or die "Can't create subdir: $!";
>         mkdir("subdir/foo") or die "Can't create subdir/foo: $!";
> mkdir("file") or die "Can't create file: $!";
>         open my $ofh, '>', "file/bar" or die "Can't create file/bar: $!";
> close $ofh;
> mkdir("dotfile") or die "Can't create dotfile: $!";
>         open my $ofh2, '>', "dotfile/.baz" or die "Can't create dotfile/.baz:
> $!"; close $ofh2;
>
> for my $dir(qw/emptysubdir file dotfile/) {
>         print is_empty1($dir) ? "$dirisempty\n" : "$diris notempty\n";
>         print is_empty2($dir) ? "$dirisempty\n" : "$diris notempty\n";
>
> }
>
> sub is_empty1 {
>   my $dir= shift;
>   my @contents = grep { ! /^$dir\/\.\.?$/ } glob("$dir/* $dir/.*");
>   return @contents == 0;
>
> }
>
> sub is_empty2 {
>   my $dir= shift;
>   opendir my $dh, $diror die "Cannot open $dir: $!";
>   my @contents = grep { ! /^\.\.?$/ } readdir($dh);
>   return @contents == 0;}
>
> __END__
>
> Results:emptyisemptyemptyisempty
> subdir is notempty
> subdir is notempty
> file is notempty
> file is notempty
> dotfile is notempty
> dotfile is notempty
>
> This is perl, v5.10.0 built for MSWin32-x86-multi-thread
>
> Paul Lalli

Thank you all for your posts. The second version works better when the
file path looks like "\\server\subDirL1\subDirl2\...".
I find Python version a bit more readable:
import os
def dirEmpty(path):
    return len(os.listdir(path)) == 0
Still, it is too bad that in either language there is no simple API
call that would return a simple True/False answer that I am looking
for ...


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to