我正在用 perl 草莓写一个脚本。它需要能够做的第一件事是获取路径参数并获取该路径的目录列表,并且它需要能够区分文件和文件夹。我阅读了有关该主题的一些教程并编写了下面的脚本,但它仅在我为其提供脚本当前所在的路径时才有效。如果我为其提供任何其他路径,则 -f 和 -d 测试不起作用.
编辑:澄清:如果我给它一个不是它自己的路径,脚本确实将所有文件和文件夹放入@thefiles,它只是 -f 和 -d 测试不起作用。
use Getopt::Long;
my $dir;
GetOptions('-d=s' => \$dir);
opendir(DIR, $dir) or die "BORKED";
@thefiles = readdir(DIR);
print DIR;
closedir(DIR);
@filez;
@dirz;
foreach $file (@thefiles){
if (-f$file){
push(@filez, $file);
}
if (-d$file){
push(@dirz, $file);
}
}
print "files: @filez \n";
print "Directories: @dirz \n";
这是截图:http://i.stack.imgur.com/RMmFz.jpg
希望有人可以提供帮助,非常感谢您的时间。 :)
最佳答案
马丁克莱顿告诉你你的代码不起作用的原因。
这是一种使用 map 修复它的方法以及一些更现代的 Perl 结构:
use strict;
use warnings;
use Getopt::Long;
my $dir;
GetOptions('-d=s' => \$dir);
opendir my $dh, $dir or die "BORKED: $!";
my @thefiles = map { "$dir/$_" } readdir $dh;
closedir $dh;
my @filez;
my @dirz;
for my $file (@thefiles) {
push @filez, $file if -f $file;
push @dirz , $file if -d $file;
}
print "files: @filez \n";
print "Directories: @dirz \n";
关于perl - Win32 Perl - 使用传递的目录参数区分文件和文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3561684/