Arrays 如何获取嵌套foreach循环中的匹配计数器?
我试图获取嵌套foreach循环中的匹配数,但计数器始终设置为0。我怎样才能解决它Arrays 如何获取嵌套foreach循环中的匹配计数器?,arrays,regex,perl,nested-loops,Arrays,Regex,Perl,Nested Loops,我试图获取嵌套foreach循环中的匹配数,但计数器始终设置为0。我怎样才能解决它 my $file_counter = 0; checkFilesInDirectory($den_file_input, $array_regex_tot, $expected_file_num); sub checkFilesInDirectory { my ($dir_path, $array_reg, $expected_file_number) = @_; opendir (DIR, $d
my $file_counter = 0;
checkFilesInDirectory($den_file_input, $array_regex_tot, $expected_file_num);
sub checkFilesInDirectory {
my ($dir_path, $array_reg, $expected_file_number) = @_;
opendir (DIR, $dir_path) or die "Can't open $dir_path: $!";
my @file = readdir(DIR);
foreach my $file (@file) {
foreach my $regex (@array_regex) {
if ($file =~ $regex) {
$file_counter++;
}
}
}
if ($file_counter < $file_previsti) {
print "\nKO All'interno di $dir_path non e presente il numero di file previsti ($file_previsti).\n";
# &ExitWithError($msg);
} elsif ($file_counter == $expected_file_number) {
print "\nOK " . substr(gmtime(time()), 11, 8) . "\n";
# &ExitWithSuccess($msg);
} elsif ($file_counter > $expected_file_number) {
print "\nWARNING All'interno di $dir_path sono presenti piu di file ($file_counter) di quelli previsti ($file_previsti).\n";
# &ExitWithSignal($msg);
}
closedir(DIR);
}
my$file\u计数器=0;
checkFilesInDirectory($den\u file\u input、$array\u regex\u tot、$expected\u file\u num);
子checkFilesInDirectory{
我的($dir\u path,$array\u reg,$expected\u file\u number)=@;
opendir(DIR,$DIR_path)或die“无法打开$DIR_path:$!”;
my@file=readdir(DIR);
foreach my$文件(@file){
foreach my$regex(@array\u regex){
如果($file=~$regex){
$file_counter++;
}
}
}
如果($file\u counter<$file\u previsti){
打印“\nKO All'interno di$dir\u path non e presente il numero di file previsti($file\u previsti)。\n”;
#&ExitWithError($msg);
}elsif($file\u counter==$expected\u file\u number){
打印“\nOK”.substr(gmtime(time()),11,8)。“\n”;
#&ExitWithSuccess($msg);
}elsif($file\u counter>$expected\u file\u number){
打印“\n警告所有内部数据$dir\u路径sono presenti piu di文件($file\u counter)di quelli previsti($file\u previsti)。\n”;
#&ExitWithSignal($msg);
}
closedir(DIR);
}
如果不看更多的代码,就很难给出详细的建议。但有一件事突然向我跳了出来:当你在子程序开始时解包@
时,你把第二个参数放入一个标量变量$array\u reg
;但在代码中的任何地方都不使用该变量,而是在遍历正则表达式列表时,使用名为@array\u regex
的数组变量。这应该是@$array\u reg
?您的代码中是否有使用严格
和使用警告
?添加它们总是一个好主意,因为它们会指出这样的错误
我还不明白为什么要在子程序之外声明
$file\u counter
。当使用子例程时(在任何语言中,不仅仅是Perl),一个好的经验法则是,子例程永远不要访问在子例程之外定义的变量。如果需要访问子例程中的数据,则将其作为额外参数传递。如果要更新该变量,则从子例程返回下一个值。让问题中的代码独立运行会很有帮助。事实上,您正在读取一个目录和测试文件并不重要。您可以将@file
作为示例的静态列表,还可以使用简单的模式(如qw(foo-bar-bz)
)包含@array\u regex
)来演示问题所在。您的问题是如何进行这些更改。它将帮助我们运行您的代码来重现问题,您可能会在尝试重现问题时自己发现问题。如果计数器保持在0,则可能没有匹配项。将一些用于调试的print
语句粘贴到该循环和if
块中,然后打开re'debug'
,查看它是否运行并匹配。您也没有使用$array\u reg
。您已经在sub之外声明了$file\u counter
,因此基本上您正在访问一个全局变量。如果您运行此sub两次,将得到错误的结果。将声明放入sub中,并使用return$file\u counter
获取计数。此外,@array\u regex
不会在任何地方声明。您将标量$array\u reg
传递给子对象,但从未使用过它。