Perl中是否有一个列出目录中所有文件和目录的函数?我记得Java有File.list()这个吗?在Perl中是否有类似的方法?
我想ls在Perl程序中执行作为CGI脚本的一部分.为此,我使用了exec(ls),但这不会从exec通话中返回.
有没有更好的方法来获取Perl中的目录列表?
我经常使用类似的东西
my $dir="/path/to/dir";
opendir(DIR, $dir) or die "can't open $dir: $!";
my @files = readdir DIR;
closedir DIR;
Run Code Online (Sandbox Code Playgroud)
或者有时我会使用glob,但无论如何,我总是需要添加一两行来过滤掉.,..这很烦人.你通常如何处理这项共同任务?
为了在Windows中列出pathes,我写了下面的Perl函数(在StrawBerry运行时环境下执行).
sub listpath
{
my $path = shift;
my @list = glob "$path/*";
#my @list = <$path/*>;
my @pathes = grep { -d and $_ ne "." and $_ ne ".." } @list;
}
Run Code Online (Sandbox Code Playgroud)
但它无法正确解析包含空间的目录,例如:
当我发出以下代码时:listpath("e:/ test/test1/test11/test111/test1111/test11111 - Copy");
该函数返回一个包含两个元素的数组:
1:e:/ test/test1/test11/test111/test1111/test11111 2: -
我想知道glob是否可以解析空间目录.非常感谢.
我从这个简单的代码开始,它通过/ home /并确定对象是文件还是目录
#!/usr/bin/perl
# My Starting directory. I could also read this from the command line
$start = "/home/";
$count = 0; # How many non-file objects found. Line un-necessary
# Initialize the list
push (@dirs, $start);
# Iterate through the list (really a queue)
# We could also do this with a shift, but this works
foreach $curr (@dirs)
{
# Get the directory listing for the current directory
# Note that -F appends a character for the …Run Code Online (Sandbox Code Playgroud)