1

我有一个问题,我希望有人能解释一下...

在我的程序中,我有两个包含大部分代码的主要子例程,然后从这些子例程中调用/引用其他执行较小任务的较小子例程,例如删除某些文件夹,将某些内容打印到屏幕等等。

我的问题示例(为了解释而大大简化):

use warnings;
use strict;

sub mainprogram {

    my @foldernames = ("hugefolder", "smallfolder", "giganticfolder");

    SKIP:foreach my $folderName (@foldernames) {
             eval {    
                 $SIG{INT} = sub { interrupt() };     #to catch control-C keyboard command
                 my $results = `grep -R hello $folderName`;  #this takes a long time to grep if its a big folder so pressing control-c will allow the user to skip to the next folder/iteration of the foreach loop
             } 

             print "RESULTS: $results\n";

    }

}

sub interrupt {

     print "You pressed control-c, do you want to Quit or Skip this huge folder and go onto greping the next folder?\n";
     chomp ($quitOrSkip = <STDIN>);
     if ($quitOrSkip =~ /quit/) {
         print "You chose to quit\n";
         exit(0);
     } elsif ($quitOrSkip =~ /skip/) {
         print "You chose to skip this folder and go onto the next folder\n";
         next SKIP;   # <-- this is what causes the problem
     }  else {
         print "Bad answer\n";
         exit(0);
     }

} 

我遇到的问题

正如您在上面的代码中看到的那样,如果用户在反引号 grep 命令在文件夹上运行时按下ctrl+ c,那么它将为他们提供完全退出程序或选择移动到 arrayloop 中的下一个文件夹并开始 greping 的选项.

使用上面的代码,您将不可避免地得到“下一个 SKIP 未找到标签...在行...”错误,因为它显然无法在另一个子例程中找到 SKIP 标签。

有没有办法可以做到这一点或达到相同的效果,即即使“下一个跳过”和“跳过:foreach”标签位于不同的子例程中,也可以进行 foreach 循环的下一次迭代。

我很清楚我可以组合这两个子例程,因此“下一个 SKIP”与“SKIP:foreach”在同一个块中,因此它可以工作,但是如果一个程序多次调用“中断”子例程并且很多次那么这将意味着很多重复的代码。

我很可能忽略了一些非常明显的事情,但是非常感谢您的帮助,谢谢

4

1 回答 1

2

您可以将打印结果移到eval, 然后die如果您不想打印它们。

foreach my $folderName (@foldernames) {
    eval {    
        local $SIG{INT} = sub { interrupt() };     #to catch control-C keyboard command
        my $results = `grep -R hello $folderName`;  #this takes a long time to grep if its a big folder so pressing control-c will allow the user to skip to the next folder/iteration of the foreach loop
        print "RESULTS: $results\n";
        1;
    } or do {
        # handle the skip if required
    };
}

sub interrupt {
    ...
    die 'skip';
    ...
}

或者:

foreach my $folderName (@foldernames) {
    eval {    
        local $SIG{INT} = sub { interrupt() };     #to catch control-C keyboard command
        my $results = `grep -R hello $folderName`;  #this takes a long time to grep if its a big folder so pressing control-c will allow the user to skip to the next folder/iteration of the foreach loop
        1;
    } or do {
        next; # Interrupted (or something went wrong), don't print the result.
    };
    print "RESULTS: $results\n";
}

sub interrupt {
    ...
    die 'skip';
    ...
}
于 2013-08-07T16:20:05.723 回答