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 is empty (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 create empty: $!";
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/empty subdir file dotfile/) {
        print is_empty1($dir) ? "$dir is empty\n" : "$dir is not empty\n";
        print is_empty2($dir) ? "$dir is empty\n" : "$dir is not empty\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, $dir or die "Cannot open $dir: $!";
  my @contents = grep { ! /^\.\.?$/ } readdir($dh);
  return @contents == 0;
}
__END__

Results:
empty is empty
empty is empty
subdir is not empty
subdir is not empty
file is not empty
file is not empty
dotfile is not empty
dotfile is not empty


This is perl, v5.10.0 built for MSWin32-x86-multi-thread


Paul Lalli


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


Reply via email to