[英]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.