简体   繁体   中英

How to develop a script in perl which can delete the data in sub folders recursively and also the parent directory?

Hi have the folder structure as follows

mishel/      #Parent directory  
      mike1  #sub file of mishel  
      minni1 #sub file of mishel  
      rosy1  #sub file of mishel
        rocky/      #sub directory of mishel
             missi  #subfile of rocky
             marsh  #subfile of rocky
             milly  #subfile of rocky 
               monu/     #sub directory of rocky
                  mike  #sub file of monu
                  minni #sub file of monu
                  rosy  #sub file of monu

so here is my question: I want to use a script which automatically deletes all the files and sub folders at a single shot.

If we use the function "rmdir(dirname)" the directory must empty. So is there any chance of deleting starting from the sub directory to the parent directory.

Write a function that takes a directory as an argument. Have that function do a readdir in the directory. For each item returned by readdir, check if it's a file - if so, delete it. If it's a directory, call the function again with the subdirectory as an argument. If there are no items (other than . and .. ), delete the directory.

use Path::Class;
my $dir = dir('foo');
$dir->recurse(callback => sub {
    unlink $_[0] if !$_[0]->is_dir;
});
$dir->rmtree(0, 1);

Or :

use File::Path ('rmtree');
rmtree('foo', 0, 0);

See http://www.perlmonks.org/bare/?node_id=605930

perl -e 'system "find mishel -delete"'

尝试使用File::Path模块的remove_tree函数

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM