perl - Win32 Perl - 使用传递的目录参数区分文件和文件夹

标签 perl file directory path

我正在用 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/

相关文章:

linux - 如何创建没有所有文件夹的 tar.gz

Perl:将序列化哈希通过管道传递给 fork 进程

multithreading - 如何在 Perl 线程中使用数组引用?

windows - 在 Windows 中,如何比较两个文件并只返回第二个文件中丢失的记录,这些记录最初存在于第一个文件中?

c - 在 C 中从文件中读取长行时处理内存

php - 使用 PHP 代码在客户端服务器中检查是否允许创建新文件/文件夹

java - 如何使用 Java 压缩/解压缩文件夹及其所有文件和子目录?

perl - grep 变量并给出信息输出

c - 在 C 中将结构写入文件时的额外零

ruby-on-rails - File.read 返回 nil