How do I break out of a loop in Perl?

前端 未结 5 1031
遥遥无期
遥遥无期 2020-12-02 04:59

I\'m trying to use a break statement in a for loop, but since I\'m also using strict subs in my Perl code, I\'m getting an error saying:

5条回答
  •  一向
    一向 (楼主)
    2020-12-02 05:54

    Simply last would work here:

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

    If you have nested loops, then last will exit from the innermost loop. Use labels in this case:

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

    Given a last statement will make the compiler to come out from both the loops. The same can be done in any number of loops, and labels can be fixed anywhere.

提交回复
热议问题