我正在尝试编写一个 perl 脚本,它检查当前目录中的所有目录,然后相应地渗透到后续目录中,直到它包含最后一个目录。这是我写的:
#!/usr/bin/perl -w
use strict;
my @files = <*>;
foreach my $file (@files){
if (-d $file){
my $cmd = qx |chown deep:deep $file|;
my $chdir = qx |cd $file|;
my @subfiles = <*>:
foreach my $ subfile(@subfiles){
if (-d $file){
my $cmd = qx |chown deep:deep $subfile|;
my $chdir = qx |cd $subfile|;
. # So, on in subdirectories
.
.
}
}
}
}
现在,我拥有的一些目录包含大约 50 个子目录。不写50 if条件怎么能穿透呢?请建议。谢谢。
最佳答案
好吧,CS101 方法(如果这只是一个练习)是使用递归函数
sub dir_perms {
$path = shift;
opendir(DIR, $path);
my @files = grep { !/^\.{1,2}$/ } readdir(DIR); # ignore ./. and ./..
closedir(DIR);
for (@files) {
if ( -d $_ ) {
dir_perms($_);
}
else {
my $cmd = qx |chown deep:deep $_|;
system($cmd);
}
}
}
dir_perms(".");
但我也会查看 File::Find 以获得更优雅和更健壮的东西(这可能会陷入循环链接陷阱,如果您不在目录上调用它,则会出错,等等),并且就此而言,我会查看普通的旧 UNIX find(1),它可以完全按照您尝试使用 -exec 选项执行的操作,例如
/bin/bash$ find /path/to/wherever -type f -exec chown deep:deep {} \;
关于linux - Perl 检查子目录并更改所有权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20703854/