Jak wyrwać się z pętli w Perlu?

Próbuję użyć instrukcji break W pętli for, ale ponieważ używam również ścisłych sub w kodzie Perla, dostaję błąd mówiąc:

Bareword "break" niedozwolony podczas "strict subs" w użyciu na. /final.pl linia 154.

Czy istnieje obejście tego problemu (oprócz wyłączenia strict subs)?

Mój kod jest sformatowany w następujący sposób:

for my $entry (@array){
    if ($string eq "text"){
         break;
    }
}
Author: Peter Mortensen, 2008-11-19

4 answers

Znalazłem. Używasz last zamiast break

for my $entry (@array){
    if ($string eq "text"){
         last;
    }
}
 383
Author: Zain Rizvi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-05 17:41:18

Dodatkowe dane (jeśli masz więcej pytań):

FOO: {
       for my $i ( @listone ){
          for my $j ( @listtwo ){
                 if ( cond( $i,$j ) ){

                    last FOO;  # --->
                                   # |
                 }                 # |
          }                        # |
       }                           # |
 } # <-------------------------------
 167
Author: Kent Fredric,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-16 20:28:21

Po Prostu last zadziałałoby tutaj:

for my $entry (@array){
    if ($string eq "text"){
         last;
    }
}

Jeśli masz zagnieżdżone pętle, to last wyjdzie z najbardziej wewnętrznej. Użyj etykiet w tym przypadku:

LBL_SCORE: {
       for my $entry1 ( @array1 ){
          for my $entry2 ( @array2 ){
                 if ( $entry1 eq $entry2 ){   # or any condition
                    last LBL_SCORE;
                 }
          }
       }
 }

Podane last polecenie sprawi, że kompilator wyjdzie z obu pętli. To samo można zrobić w dowolnej liczbie pętli, a etykiety można przymocować w dowolnym miejscu.

 14
Author: Kamal Nayan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-09 14:32:50

Na dużej iteracji lubię używać przerwań. Po prostu naciśnij Ctrl + C zamknąć:

my $exitflag = 0;
$SIG{INT} = sub { $exitflag=1 };

while(!$exitflag) {
    # Do your stuff
}
 3
Author: MortenB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-20 17:40:08