Jair Santos wrote: > > From: "Charles K. Clarkson" <[EMAIL PROTECTED]> > > > Jair Santos [mailto:[EMAIL PROTECTED] wrote: > > : > > : I am using the following snippet of code to > > : check if the directory is empty : and it is > > : working. > > : > > : sub IsEmptyDir { > > : > > : my ( $directory) = @_ ; > > > > You don't need that line. > > > > : return undef unless -d $_[0]; > > : opendir my $dh, $_[0] or die $!; > > : my $count = () = readdir $dh; > > : return $count - 2; > > : } > > > > As Rob Dixon pointed out, this is less > > than the safest algorithm. Instead of > > decrementing the count, the "." and ".." > > files should be specifically excluded. I > > would recommend this modification. > > > > sub IsEmptyDir { > > return undef unless -d $_[0]; > > opendir my $dh, $_[0] or die $!; > > my $count = () = grep ! /^\.{1,2}/, readdir $dh;
You don't need to use the =()= trick with grep() because grep() returns a list which will evaluate to the number of elements in the list in a scalar context. Also you should anchor the regular expression at the end as well as the beginning (/^\.{1,2}$/) to be correct. $ perl -le' @array = qw/a b c d e f/; $count = @array; print $count; $count = grep !/c/, @array; print $count; ' 6 5 > > return $count ? 0 : 1; You could just return $count; which will do the right thing. > > } > > > > This also changes the logic to return > > true when $count is 0. Which would allow: > > > > print "Empty Directory\n" if IsEmptyDir( $foo_dir ); > > as a begginer I am having some problems to understand this compact code perl > let us write. > > In my script I was testing like this if (IsEmptyDir($directory) = = 0) > and, when I included the new code you suggested, it didn work. Then I > removed the = = 0 and started to work. That is because "= =" is a syntax error, it should be "==" with no whitespace between the two equals signs. Since the expression is in a boolean context the "== 0" part can be omitted and it will do the same thing. > Could you explain what exactly this part of the line does. grep ! > /^\.{1,2}/ > > Is it a search over the readdir result set ? grep() evaluates the expression on every element of a list on the right hand side and if that expression is true it passes the element through to the left hand side. So any file name that does not begin with one or two dots will be used in the count. Of course on Unix there could be a lot of files that begin with one dot that will not be included in that count. John -- use Perl; program fulfillment -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]