0

我已经以多种方式将我的代码简化为最基本的内容,试图找出为什么我的数组中的第一个值是空白的,我很困惑。我有一系列目录和文件。如果它是名称包含某个字符串(如“conf”)的目录或文件,我不感兴趣。如果是其他内容,我将其写入屏幕并将其推送到数组对象。

然后,我遍历数组并将每个条目写入屏幕。这就是我想要做的。当我查看第一部分中打印到屏幕上的内容时,信息与我预期的一样。当我打印出数组中的条目时,输出总是有一个空字符串,或者在数组的第一个索引中没有任何内容。

这是我的代码:

sub scrubFiles { # Parse through interesting directories for interestingly named files
    my $wanted = sub {
            if (-d $_) {
                    print "Directory and will not be inserted into the files array: $_\n"
                    return;
            };
            if ($_ =~ /\.(?:yaml|bak|conf|cfg)\z/i) {
                    print "Not desirable and will not be inserted into the files array: $_\n";
                    return;
            };
            print ("Adding $_ to \@filelist\n");
            push @filelist, $File::Find::name;
    };
    find( {wanted => $wanted, no_chdir=>1}, @_ );  # WILL NOT work properly without no_chdir
    return @filelist;
}

&scrubFiles("/tmp/mydirectory/");
for (@filelist) { print "File name: $_|END\n"; }

推送到数组时,我得到以下输出。“<...>”是我刚刚删除的输出,因为它无关紧要。“添加”部分正是我所期望的。在第一个“添加”打印到屏幕之前没有任何内容。当它到达“文件名”部分时,它与我所期望的完全一样,除了打印到屏幕上的数组中的第一个条目是空白的,如您在此处看到的:

Adding /tmp/mydirectory/ifconfig.txt to @filelist
Adding /tmp/mydirectory/history_comp.txt to @filelist
Adding /tmp/mydirectory/myctl.txt to @filelist
Adding /tmp/mydirectory/ls-l.txt to @filelist
<...>
Adding /tmp/mydirectory/opt/comp/VERSION to @filelist
File name: |END
File name: /tmp/mydirectory/ifconfig.txt|END
File name: /tmp/mydirectory/history_comp.txt|END
File name: /tmp/mydirectory/myctl.txt|END
File name: /tmp/mydirectory/ls-l.txt|END
<...>
File name: /tmp/mydirectory/opt/comp/VERSION|END

我尝试使用“ref()”来找出位置 0 中的实际内容,但它不会为数组中的每个条目返回任何内容。

有什么想法可以让我得到这个空白条目吗?

4

1 回答 1

1

您之前的代码具有适当范围的变量。你打破了那个。通过回到使用全局变量,我们必须查看程序中的每一行才能知道发生了什么。那将是愚蠢的。

Start by going back to the code you were given to undo the two bugs you introduced. Declare @filelist in the sub, and actually use the list returned by the sub.

于 2013-01-11T20:50:12.567 回答