【问题标题】:How can I get the counter of matches inside nested foreach loop?如何在嵌套的 foreach 循环中获取匹配的计数器?
【发布时间】:2021-03-18 17:35:46
【问题描述】:

我试图在嵌套的 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, $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);
}

【问题讨论】:

  • 让问题中的代码独立运行会很有帮助。您正在阅读目录和测试文件这一事实并不重要。您可以将@file 设为示例的静态列表,还可以将@array_regex 包含在简单的模式中(如qw(foo bar bz))以演示问题所在。 Edit您提出这些更改的问题。它将帮助我们运行您的代码来重现问题,并且您可能在尝试重现问题时自己发现问题。
  • 如果计数器保持在 0,则可能不匹配。将一些 print 语句用于调试到该循环和 if 块中,然后打开 re 'debug' 以查看它是否运行并匹配。你也没有使用$array_reg
  • 您已经在您的子系统之外声明了$file_counter,所以基本上您正在访问一个全局变量。如果你运行这个 sub 两次,你会得到错误的结果。将声明放入 sub 中,并使用return $file_counter 获取计数。
  • 另外,@array_regex 没有在任何地方声明。您将标量 $array_reg 传递给 sub,但您从不使用它。

标签: arrays regex perl nested-loops


【解决方案1】:

如果不查看更多代码,很难给出详细的建议。但是有一件事突然出现在我身上:当您在子程序开始时解包@_ 时,您将第二个参数放入一个名为$array_reg 的标量变量中;但是您不会在代码中的任何地方使用该变量,而是在迭代正则表达式列表时使用名为@array_regex 的数组变量。这应该是@$array_reg 吗?你的代码中有use strictuse warnings 吗?添加它们总是一个好主意,因为它们会指出这样的错误。

我也很困惑你为什么在你的子程序之外声明$file_counter。当使用子例程时(在任何语言中——不仅仅是 Perl),一个很好的经验法则是子例程不应该访问在子例程之外定义的变量。如果您需要在子例程中访问该数据,则将其作为额外参数传递。如果您想更新该变量,请从您的子程序中返回下一个值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 2012-05-16
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    相关资源
    最近更新 更多