On Mon, Jun 28, 1999 at 12:31:29PM -0700, Jeremy Andrews wrote: > >From owner-macperl-anyperl@cfcl.com Sun Jun 27 01:13:38 1999 sorry for > >the delay] > Message-Id: <v04205102b39b8a65bdbb@[199.165.65.84]> > In-Reply-To: <199906261100.EAA05753@cfcl.com> > References: <199906261100.EAA05753@cfcl.com> > Date: Sun, 27 Jun 1999 00:05:06 -0800 > > Hello, > > Is there a good way to recursively delete a directory and all of its > subdirectories? I've attempted to do this with the following code, > but it doesn't work. (I'm programming this on my Mac, but it's > intended to work on a Apache UNIX machine...) > > ########## > # Recursively delete directory > # routine is called by passing in a directory to be deleted, in $_[0] > # > sub delete_directory { > opendir(DIRECTORY, "$_[0]") or die; You should include a useful error message when you die. The quotes around $_[0] are superfluous. > @directories = grep !/\./, readdir DIRECTORY; You can't have directories with periods in their names? How curious... > unless (@directories eq "") { @directories will _never_ eq "". In a scalar context, an array evaluates to the number of elements in the array. This will be 0 if the array is empty, or a positive integer if the array is not empty, but certainly never the null string. > foreach $directory (@directories) { delete_directory > ($_[0]/$directory); } Take those quotes you used around $_[0] before, and put them around $_[0]/$directory here. I really don't think you meant to do a division here... :) Where's the code that checks whether the items in @directories _really are_ directories? If you try to delete_directory a file that is not a directory, then delete_directory will die in the first line. Hint: You need to use the -d filetest operator. > } > @files = readdir DIRECTORY; If you want to read from DIRECTORY again, you need to rewinddir() first. On the other hand, you never localized the dirhandle, so each call to delete_directory clobbers the previous call's dirhandle. One solution would be to localize the DIRECTORY glob: local(*DIRECTORY); Another would be to reopen the appropriate directory when you need to read from it a second time. A third solution would be to read all the names once, and separate them into two arrays, one for directories and one for files. Then you won'y have to read from the dirhandle again. > unlink @files; You should die if the unlink fails (and include a useful error message). > rmdir $_[0] or die; You should include a useful error message when you die. > } > # > ########## > Instead of writing the solution from scratch, I would recommend using the finddepth() function from the File::Find module. Ronald ==== Want to unsubscribe from this list? ==== Send mail with body "unsubscribe" to macperl-anyperl-request@macperl.org