5plit_func has asked for the wisdom of the Perl Monks concerning the following question:

I am have difficulty deleting a file from my computer hard disk the file is a .dat file and its located in the users/all users/Norton folder. I want to delete the contents of the folder and sub folder till i delete the Norton folder. Here is the sample code

opendir(DIR, "$path/$new_folder/$new_folder1/$third_layer") || die("Un +able to opend $third_layer : $!\n\n"); my @third_layer = readdir(DIR); closedir(DIR); print("Third layer is : @third_layer\n\n"); shift(@third_layer); shift(@third_layer); print("@third_layer\n\n"); @third_layer = map{ $_ = "$path/$new_folder/$new_folder1/$third_layer/ +$_"}@third_layer; if(unlink(@third_layer)) { print("Successfully deleted the following data : @third_layer\n\n" +); }else { print("Unable to delete the following data : @third_layer\n\n"); }

Any help will be highly appreciated.

  • Comment on unable to delete dat files from a folder in windows all users/norton folder
  • Download Code

Replies are listed 'Best First'.
Re: unable to delete dat files from a folder in windows all users/norton folder
by Corion (Patriarch) on Nov 16, 2013 at 17:14 UTC

    Instead of trying to unlink all files in one go, have you looked at unlinking them one by one and inspecting $! for the error reason if there is an error? See unlink and perlvar on $!.

Re: unable to delete dat files from a folder in windows all users/norton folder
by kcott (Archbishop) on Nov 16, 2013 at 17:34 UTC

    G'day 5plit_func,

    Look at readdir for better and more concise ways to achieve what you're doing with respect to getting a listing of files. I suspect the two shifts are to remove the current and parent directories (i.e. '.' and '..'): the grep in the first example removes the need for these statements as well as the additional map in your code.

    I'd recommend using the autodie pragma to check for problems (including opendir and unlink). The alternative is to hand-craft explicit checks throughout your code: this is time consuming, a lot more work and error-prone.

    If the errors that now show up do not help you, please post them here so that we can see them. While it's good that you've posted your code, without seeing the output, error or otherwise, we're somewhat in the dark with regards to being able to provide help. [Take a look at the guidelines in "How do I post a question effectively?" if you're unsure what to post.]

    If you're not doing this already, I'd strongly recommend setting up a test directory (perhaps with a script to recreate it) for trying out your code while you're in development mode. It's all too easy to accidently delete the wrong (possibly important) files.

    -- Ken

      glob / File::Glob is an even more concise way to get a directory listing.