获取给定路径下的目录名称

Nig*_*ker 4 perl

我试图获取给定路径下所有第一级目录的名称.

我试图使用File :: Find但有问题.

有人可以帮助我吗?

inn*_*naM 24

使用-d文件检查操作符:

#!/usr/bin/perl

use strict;
use warnings;
use autodie;

my $path = $ARGV[0];
die "Please specify which directory to search" 
    unless -d $path;

opendir( my $DIR, $path );
while ( my $entry = readdir $DIR ) {
    next unless -d $path . '/' . $entry;
    next if $entry eq '.' or $entry eq '..';
    print "Found directory $entry\n";
}
closedir $DIR;
Run Code Online (Sandbox Code Playgroud)

  • 是的,它可能会错过名为"0"的目录.我现在可以请下一个downvote,因为我没有发布单元测试吗?如果有人在脚本运行时拔出硬盘驱动器的插头怎么办? (6认同)
  • 好.所以我编辑了这个来检查opendir的返回值.我拒绝检查closedir的返回值,除非有人告诉我脚本应该做什么应该closedir失败. (3认同)
  • 那就是为什么你投了这个呢?今天到底出了什么问题? (2认同)

FMc*_*FMc 7

如果您不需要遍历整个目录层次结构,File :: SlurpFile :: Find更容易使用.

use strict;
use warnings;
use File::Slurp qw( read_dir );
use File::Spec::Functions qw( catfile );

my $path = shift @ARGV;
my @sub_dirs = grep { -d } map { catfile $path, $_ } read_dir $path;
print $_, "\n" for @sub_dirs;
Run Code Online (Sandbox Code Playgroud)

如果您确实需要遍历层次结构,请检查CPAN是否有更友好的替代方案File::Find.

最后,根据TIMTOWTDI的精神,这里有一些快速和肮脏的东西:

my @sub_dirs = grep {-d} glob("$ARGV[0]/*");
Run Code Online (Sandbox Code Playgroud)