代码之家  ›  专栏  ›  技术社区  ›  adhanlon

如何在Perl中循环遍历目录中的文件?[重复]

  •  25
  • adhanlon  · 技术社区  · 16 年前

    可能重复:
    How can I list all of the files in a directory with Perl?

    我想循环浏览几百个文件,它们都包含在同一个目录中。在Perl中如何实现这一点?

    3 回复  |  直到 9 年前
        1
  •  51
  •   Sam B    7 年前
    #!/usr/bin/perl -w
    
    my @files = <*>;
    foreach my $file (@files) {
      print $file . "\n";
    }
    

    哪里

     @files = <*>;
    

    可以是

     @files = </var/www/htdocs/*>;
     @files = </var/www/htdocs/*.html>;
    

        2
  •  21
  •   Community Mohan Dere    14 年前

    享受

    opendir(DH, "directory");
    my @files = readdir(DH);
    closedir(DH);
    
    foreach my $file (@files)
    {
        # skip . and ..
        next if($file =~ /^\.$/);
        next if($file =~ /^\.\.$/);
    
        # $file is the file used on this iteration of the loop
    }
    
        3
  •  13
  •   Sinan Ünür    11 年前

    你可以用 readdir glob .

    或者,您可以使用以下模块: Path::Class :

    通常地 children() 将不包括自我和父项。和(或在非Unix系统上的等价物),因为这就像是我自己的生意。如果确实需要所有目录条目,包括这些特殊条目,请为all参数传递一个真值:

    @c = $dir->children(); # Just the children
    @c = $dir->children(all => 1); # All entries
    

    此外,还有一个no_hidden参数,它将排除所有通常“隐藏”的条目——在Unix上,这意味着排除所有以点开头的条目( . ):

    @c = $dir->children(no_hidden => 1); # Just normally-visible entries
    

    Path::Tiny :

    @paths = path("/tmp")->children;
    @paths = path("/tmp")->children( qr/\.txt$/ );
    

    返回 Path::Tiny 一个目录中所有文件和目录的对象。排除 "." ".." 自动地

    如果是可选的 qr// 参数时,它仅返回与给定正则表达式匹配的子名称的对象。只有基名称用于匹配:

    @paths = path("/tmp")->children( qr/^foo/ );
    # matches children like the glob foo*
    

    将目录项列表放入数组会浪费一些内存(而不是一次只获取一个文件名),但如果只有几百个文件,这不太可能成为问题。

    Path::Class 可移植到*nix和Windows以外的操作系统。另一方面,在AFAIK中,其实例使用的内存比 路径:微小的 实例。

    如果内存有问题,最好使用 readdir 在一个 while