Win32 Perl - 使用传递的目录参数区分文件和文件夹之间的区别
我正在用 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";
这是一个屏幕截图: https://i.sstatic.net/RMmFz.jpg
希望有人可以帮助并非常感谢您的宝贵时间。 :)
I'm writing a script in perl strawberry. The first thing it needs to be able to do is take a path argument and get a directory listing for that path, and it needs to be able to distinguish between files and folders. I read some tutorials on the subject and wrote the script below, but it only works when I give it the path that the script is currently residing in. If I give it any other path, the -f and -d tests don't work.
EDIT: Clarification: The script DOES put all the files and folders into @thefiles if I give it a path other than it's own, it's just the -f and -d tests that don't work.
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";
Here's a screenshot: https://i.sstatic.net/RMmFz.jpg
Hope someone can help and thanks very much for your time. :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
马丁·克莱顿告诉你你的代码不起作用的原因。
以下是使用 map 和一些更现代的 Perl 构造来修复它的方法:
martin clayton told you the reason your code does not work.
Here is a way to fix it using map and some more modern Perl constructs:
这是因为 filetest
-f
和-d
运算符使用相对路径,除非您提供绝对路径。 readdir 函数将返回在目录中找到的文件(和子目录...)名称,但不是完整路径。来自文档:
It's because the filetest
-f
and-d
operators use a relative path unless you provide an absolute one. Thereaddir
function will return the file (and subdirectory...) names found in the directory, but not the full paths.From the docs: