繁体   English   中英

如何检查Perl中的子子目录?

[英]How do I check for a sub-subdirectory in Perl?

我有一个名为Client的文件夹,其中包含许多子文件夹。 我想创建一个Perl脚本来查看每个子文件夹并检查那里的文件夹。 如果它在那里,我想跳过它并继续前进,如果不存在,我想创建它并进行一些处理。

如何循环遍历所有子文件夹并检查我想要的目录? 我已经找到了很多关于如何获取文件夹和/或子文件夹中的所有文件的信息,但没有检查每个子文件夹中的目录。

Augh! 其他答案太复杂了。 原始问题似乎不是要求递归遍历。 据我所知,这是一个非常明智的解决方案,并且更具可读性:

foreach my $dir (glob "Client/*") {
    next if ! -d $dir;              # skip if it's not a directory
    next if -d "$dir/subfolder";    # skip if subfolder already exists
    mkdir "$dir/subfolder" or die;  # create it
    do_some_processing();           # do some processing
}

认真的人:opendir / readdir? 真?

一旦你把它分成几步,这很容易。 获取带有glob的子目录列表,然后查看哪些没有二级目录。 如果您使用的是File :: Find-like模块,那么您可能做了太多工作:

#!perl

use strict;
use warnings;

use File::Spec::Functions;

my $start  = 'Clients';
my $subdir = 'already_there';

# @queue is the list of directories you need to process
my @queue  = grep { ! -d catfile( $_, $subdir ) }   # filter for the second level
             grep { -d }                            # filter for directories
             glob catfile( $start, '*' );           # everything below $start   
#!/usr/bin/perl

use strict;

use Fcntl qw( :DEFAULT :flock :seek );
use File::Spec;
use IO::Handle;

my $startdir = shift @ARGV || '.';
die "$startdir is not a directory\n"
    unless -d $startdir;
my $verify_dir_name = 'MyDir';

my $dh = new IO::Handle;
opendir $dh, $startdir or
    die "Cannot open $startdir: $!\n";
while(defined(my $cont = readdir($dh))) {
    next
        if $cont eq '.' || $cont eq '..';
    my $fullpath = File::Spec->catfile($dir, $cont);
    next
        unless -d $fullpath && -r $fullpath && -w $fullpath;
    my $verify_path = File::Spec->catfile($fullpath, $verify_dir_name);
    next
        if -d $verify_path;
    mkdir($verify_path, 0755);
    # do whatever other operations you want to $verify_path
}
closedir($dh);

简短的回答是使用File :: FInd。

长的答案是首先编写一个验证文件夹是否存在的子程序,如果文件夹不在那里,则创建它,然后进行所需的处理。 然后调用File :: Find模块的find方法,并引用子例程和起始文件夹来处理所有子文件夹。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM