如何在Perl中的目录中循环文件?

adh*_*lon 27 perl file

可能重复:
如何使用Perl列出目录中的所有文件?

我想循环遍历同一目录中包含的几百个文件.我如何在Perl中执行此操作?

ETo*_*reo 48

#!/usr/bin/perl -w

my @files = <*>;
foreach my $file (@files) {
  print $file . "\n";
}
Run Code Online (Sandbox Code Playgroud)

哪里

 @files = <*>;
Run Code Online (Sandbox Code Playgroud)

 @files = </var/www/htdocs/*>;
 @files = </var/www/htdocs/*.html>;
Run Code Online (Sandbox Code Playgroud)

等等


ska*_*ace 19

请享用.

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
}
Run Code Online (Sandbox Code Playgroud)

  • @ashraf 正则表达式必须是 /^\.+$/ 而不是 /^.+$/ (2认同)

Sin*_*nür 13

您可以使用readdirglob.

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

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

@c = $dir->children(); # Just the children
@c = $dir->children(all => 1); # All entries
Run Code Online (Sandbox Code Playgroud)

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

@c = $dir->children(no_hidden => 1); # Just normally-visible entries
Run Code Online (Sandbox Code Playgroud)

或者,Path :: Tiny:

@paths = path("/tmp")->children;
@paths = path("/tmp")->children( qr/\.txt$/ );
Run Code Online (Sandbox Code Playgroud)

返回目录中Path::Tiny所有文件和目录的对象列表.排除"."".."自动排除.

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

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

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

Path::Class可移植到*nix和Windows以外的操作系统.另一方面,AFAIK,其实例使用的内存比Path::Tiny实例多.

如果内存是个问题,最好readdirwhile循环中使用.