有没有办法检查文件夹中是否存在任何子文件夹。我想在Perl中做到这一点?
答案 0 :(得分:3)
通过目录的内容全局,并检查它是否是-d
的目录。
sub has_subfolder {
my $directory = shift;
for ( <$directory/*>, <$directory/.*> ) {
next if m@/\.\.?$@; # skip . and ..
return 1 if -d;
}
return 0;
}
答案 1 :(得分:3)
if (grep -d, glob("$folder/*")) {
print "$folder has subfolder(s)\n";
}
如果您想处理与.*
匹配的目录,您可以这样做:
if (grep -d && !/\.\.?$/, glob("$folder/.* $folder/*")) {
print "$folder has subfolder(s)\n";
}
答案 2 :(得分:1)
sub hasSubDir {
my $dir_name = shift;
opendir my $dir, $dir_name
or die "Could not open directory $dir_name: $!";
my @files = readdir($dir);
closedir($dir);
for my $file (@files) {
if($file !~ /\.\.?$/) {
return 1 if -d $dir/$file;
}
}
return 0;
}
答案 3 :(得分:1)
为了检查目录中是否存在子文件夹(不知道任何名称):
my $dir_name = "some_directory";
opendir my $dir, $dir_name
or die "Could not open directory $dir_name: $!";
my $has_subfolder = grep { -d && !/(^|\/)\.\.?$/ } map { ("$dir_name"||'.')."/$_" } readdir $dir;
换句话说,它会检查目录中的一个或多个文件,这些文件本身就是目录。
如果你想要一个特定的子文件夹,只需使用Geo的答案。
编辑:现在变得愚蠢,但这是一个真正的通用答案。 :-P无论如何,其他人都得到了复选标记。
答案 4 :(得分:1)
好的,我只需提交自己的答案
sub has_subfolder {
my $dir = shift;
my $found = 0;
opendir my $dh, $dir or die "Could not open directory $dir: $!";
while (my $_ = readdir($dh)) {
next if (/^\.\.?$/); # skip '.' and '..'
my $path = $dir . '/' . $_; # readdir doesn't return the whole path
if (-d $path) { # found a dir? record it, and leave the loop!
$found = 1;
last;
}
closedir($dh); # make sure we cleanup after!
return $found;
}
与其他答案相比:
编辑 - 我看到要求刚改变(叹气)。幸运的是,上面的代码经过了简单的修改:
sub get_folders {
my $dir = shift;
my @found;
opendir my $dh, $dir or die "Could not open directory $dir: $!";
while (my $_ = readdir($dh)) {
next if (/^\.\.?$/); # skip '.' and '..'
my $path = $dir . '/' . $_; # readdir doesn't return the whole path
push(@found, $_) if (-d $path) # found a dir? record it
}
closedir($dh); # make sure we cleanup after!
return @found;
}
答案 5 :(得分:1)
您可以使用'File :: Find'模块来实现此目的。 File :: Find递归处理和扫描目录。以下是示例代码:
use File::Find;
my $DirName = 'dirname' ;
sub has_subdir
{
#The path of the file/dir being visited.
my $subdir = $File::Find::name;
#Ignore if this is a file.
return unless -d $subdir;
#Ignore if $subdir is $Dirname itself.
return if ( $subdir eq $DirName);
# if we have reached here, this is a subdirector.
print "Sub directory found - $subdir\n";
}
#For each file and sub directory in $Dirname, 'find' calls
#the 'has_subdir' subroutine recursively.
find (\&has_subdir, $DirName);
答案 6 :(得分:-1)
if(-e "some_folder/some_subfolder") {
print "folder exists";
}
else {
print "folder does not exist";
}