我怎样才能用Perl来列出目录中的所有文件?

Perl中是否有函数列出目录中的所有文件和目录? 我记得Java有File.list()来做到这一点? Perl中是否有类似的方法?

如果你想获得给定目录的内容,并且只有它(即没有子目录),最好的方法是使用opendir / readdir / closedir:

 opendir my $dir, "/some/path" or die "Cannot open directory: $!"; my @files = readdir $dir; closedir $dir; 

你也可以使用:

 my @files = glob( $dir . '/*' ); 

但在我看来,它并不是很好 – 主要是因为glob是相当复杂的事情(可以自动过滤结果),并使用它来获取目录的所有元素似乎是一个太简单的任务。

另一方面,如果你需要从所有的目录和子目录中获取内容,基本上有一个标准的解决scheme:

 use File::Find; my @content; find( \&wanted, '/some/path'); do_something_with( @content ); exit; sub wanted { push @content, $File::Find::name; return; } 

或者File :: Find

 use File::Find; finddepth(\&wanted, '/some/path/to/dir'); sub wanted { print }; 

如果它们存在,它将通过子目录。

readdir()这样做。

检查http://perldoc.perl.org/functions/readdir.html

 opendir(DIR, $some_dir) || die "can't opendir $some_dir: $!"; @dots = grep { /^\./ && -f "$some_dir/$_" } readdir(DIR); closedir DIR; 

这应该做到这一点。

 my $dir = "bla/bla/upload"; opendir DIR,$dir; my @dir = readdir(DIR); close DIR; foreach(@dir){ if (-f $dir . "/" . $_ ){ print $_," : file\n"; }elsif(-d $dir . "/" . $_){ print $_," : folder\n"; }else{ print $_," : other\n"; } } 

如果你是一个像我这样的懒鬼,你可能会喜欢使用File :: Slurp模块。 read_dir函数将目录内容读入一个数组,删除这些点,如果需要的话,用绝对path

 my @paths = read_dir( '/path/to/dir', prefix => 1 ) ; 

这将从您指定的目录,顺序和属性中列出一切(包括子目录)。 我花了好几天的时间寻找这样的事情,而我从这整个讨论中拿出了一些部分,把我自己的一些部分放在一起。 请享用!!

 #!/usr/bin/perl -- print qq~Content-type: text/html\n\n~; print qq~<font face="arial" size="2">~; use File::Find; # find( \&wanted_tom, '/home/thomas/public_html'); # if you want just one website, uncomment this, and comment out the next line find( \&wanted_tom, '/home'); exit; sub wanted_tom { ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat ($_); $mode = (stat($_))[2]; $mode = substr(sprintf("%03lo", $mode), -3); if (-d $File::Find::name) { print "<br><b>--DIR $File::Find::name --ATTR:$mode</b><br>"; } else { print "$File::Find::name --ATTR:$mode<br>"; } return; }