in reply to How to tell if a Directory is Empty

use strict; use warnings; my $error; if (!dirEmpty($ARGV[0], $error)) { print $error ? "$error\n" : "Directory contains files.\n"; } else { print "Directory is empty.\n"; } sub dirEmpty { if (!-e $_[0]) { $_[1] = 'Directory does not exist.'; return; } if (!-d $_[0]) { $_[1] = 'Path does not reference a directory.'; return; } if (!opendir(DIR, $_[0])) { $_[1] = 'Could not open directory.'; return; } while ($_ = readdir(DIR)) { next if m/^\.\.?$/; return; } return 1; }

Replies are listed 'Best First'.
Re^2: How to tell if a Directory is Empty
by Anonymous Monk on Nov 27, 2011 at 08:28 UTC

    I was trying to be clever, so I discovered IO::Dir and seekdir

    I wrote this code, and then had a WTF moment

    sub dirEmpty { my $d = IO::Dir->new( @_ ); return defined( $d && $d->seek( 2 ) && scalar $d->read ); }

    seekdir is broken on my win32 machine :)