perl - 使用 Perl 删除一个非常大的文件夹的最佳策略是什么?

标签 perl file-handling

我需要删除给定文件夹下的所有内容(文件和文件夹)。问题是该文件夹中有数百万个文件和文件夹。所以我不想一次性加载所有文件名 .

逻辑应该是这样的:

  • 迭代文件夹而不加载所有内容
  • 获取文件或文件夹
  • 删除它
    (详细说明文件或文件夹“X”已被删除)
  • 转到下一个

  • 我正在尝试这样的事情:
    sub main(){
      my ($rc, $help, $debug, $root)   = ();
      $rc = GetOptions ( "HELP"           => \$help,
                         "DEBUG"          => \$debug,
                         "ROOT=s"         => \$root);
    
      die "Bad command line options\n$usage\n" unless ($rc);
      if ($help) { print $usage; exit (0); }
    
      if ($debug) {
          warn "\nProceeding to execution with following parameters: \n";
          warn "===============================================================\n";
          warn "ROOT = $root\n";
    
      } # write debug information to STDERR
    
      print "\n Starting to delete...\n";  
    
      die "usage: $0 dir ..\n" unless $root;
      *name = *File::Find::name;
      find \&verbose, @ARGV;
    
    }
    
    sub verbose {
        if (!-l && -d _) {
            print "rmdir $name\n";
        } else {
            print "unlink $name\n";
        }
    }
    
    main();
    

    它工作正常,但是每当“find”读取巨大的文件夹时,应用程序就会卡住,我可以看到 Perl 的系统内存增加直到超时。为什么?它是否试图一次性加载所有文件?

    谢谢你的帮助。

    最佳答案

    remove_tree函数来自 File::Path可以 便携详细删除目录层次结构,保持如果需要,顶级目录。

    use strict;
    use warnings;
    use File::Path qw(remove_tree);
    
    my $dir = '/tmp/dir';
    remove_tree($dir, {verbose => 1, keep_root => 1});
    

    在 5.10 之前,使用 rmtree函数来自 File::Path .如果你仍然想要顶级目录,你可以只是 mkdir再说一遍。
    use File::Path;
    
    my $dir = '/tmp/dir';
    rmtree($dir, 1);  # 1 means verbose
    mkdir $dir;
    

    关于perl - 使用 Perl 删除一个非常大的文件夹的最佳策略是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2567952/

    相关文章:

    perl - Perl 6 有污点模式吗?

    perl - Perl 进程之间共享只读内存

    Perl 成像器 : how do I make the alpha channel become black insead of white?

    linux - 使用 perl 检查仅开放的端口

    php - PRCE : substring exclusion in capturing group result

    c++写入文件

    c - 如何在算术运算中使用文件中的结构变量?

    C++ ofstream 不在程序的后续运行中创建和写入文件

    java - flush() java 文件处理

    c - 从文件中读取值并将其存储在二维矩阵中