使用 ARGV for perl 获取目录

get directories using ARGV for perl

   $args = @ARGV;

foreach $ARGV (@ARGV)
{
$guitestsDir = "v:\stuf\comment\logs\$ARGV\";

############################open logs folder#########################   
if ( -d $guitestsDir ) {
    opendir( DIR, $guitestsDir );
    while ( defined( $pathofdir = readdir(DIR) ) ) {
        next if ( $pathofdir eq "." );
        next if ( $pathofdir eq ".." );
        next unless (-d "$guitestsDir/$pathofdir");
        push (@pathallSuites, $pathofdir);
    }
    closedir(DIR);
}


print "@pathallSuites\n";

您好,我将目录 1 和 2 作为参数。在目录 1 中将是 dir a and b 在目录 2 c and d 当我 运行 它用于 print "@pathallSuites\n"; 时,输出将是:

a b
a b c d

应该是

a b
c d

我做错了什么? 谢谢

您永远不会重置 @pathAllSuites 变量。在 foreach 循环开始时,您需要自己执行此操作。

foreach $ARGV (@ARGV)
{
$#pathAllSuites = -1; # Set the 'last index' to -1, effectively clearing it.
$guitestsDir = "v:\stuf\comment\logs\$ARGV\";

直接的问题是您没有在 foreach 循环的执行之间清空 @pathallSuites,但在这背后是您没有 use strictuse warnings 'all' 就位, 必须总是 出现在你编写的每个 Perl 程序的顶部。如果你在循环

中声明它,那么 Perl 会为你重置数组

我建议您使用 glob to search for files and directories, and use the File::Spec::Functions 库来操作文件路径,而不是更容易出错的基本字符串函数

结果是更简洁的代码,如此处所示。对 grep 的调用过滤了 glob 的结果,使其只包含目录名而没有任何文件名

请注意,此程序与您自己的程序不同,输出的是每个子目录的完整路径,而不仅仅是子目录的名称。如果你真的只想要名字那么改变是微不足道的,但我认为你更有可能真的需要整个东西。如果我错了请告诉我

use strict;
use warnings 'all';

use File::Spec::Functions 'catdir';

use constant ROOT_DIR => 'V:/stuf/comment/logs';

for my $subdir ( @ARGV ) {

    my @path_all_suites = grep -d, glob catdir(ROOT_DIR, $subdir, '*');

    print "$_\n" for @path_all_suites;
    print "\n";
}

这是一个精简版,所有内容都在一行输出中:

print map( "$_ ", map( glob( "$_/*/" ), @ARGV )), "\n";

或单列:

print map( "$_\n", map( glob( "$_/*/" ), @ARGV ));