How do I break out of a loop in Perl?

前端 未结 5 1012
遥遥无期
遥遥无期 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:47

    Oh, I found it. You use last instead of break

    for my $entry (@array){
        if ($string eq "text"){
             last;
        }
    }
    
    0 讨论(0)
  • 2020-12-02 05:51

    On a large iteration I like using interrupts. Just press Ctrl + C to quit:

    my $exitflag = 0;
    $SIG{INT} = sub { $exitflag=1 };
    
    while(!$exitflag) {
        # Do your stuff
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-02 05:56

    Additional data (in case you have more questions):

    FOO: {
           for my $i ( @listone ){
              for my $j ( @listtwo ){
                     if ( cond( $i,$j ) ){
    
                        last FOO;  # --->
                                       # |
                     }                 # |
              }                        # |
           }                           # |
     } # <-------------------------------
    
    0 讨论(0)
  • 2020-12-02 05:58

    For Perl one-liners with implicit loops (using -n or -p command line options), use last or last LINE to break out of the loop that iterates over input records. For example, these simple examples all print the first 2 lines of the input:

    echo 1 2 3 4 | xargs -n1 | perl -ne 'last if $. == 3; print;'
    echo 1 2 3 4 | xargs -n1 | perl -ne 'last LINE if $. == 3; print;'
    echo 1 2 3 4 | xargs -n1 | perl -pe 'last if $. == 3;'
    echo 1 2 3 4 | xargs -n1 | perl -pe 'last LINE if $. == 3;'
    

    All print:

    1
    2
    

    The perl one-liners use these command line flags:
    -e : tells Perl to look for code in-line, instead of in a file.
    -n : loop over the input one line at a time, assigning it to $_ by default.
    -p : same as -n, also add print after each loop iteration over the input.

    SEE ALSO:

    last docs
    last, next, redo, continue - an illustrated example
    perlrun: command line switches docs


    More examples of last in Perl one-liners:

    Break one liner command line script after first match
    Print the first N lines of a huge file

    0 讨论(0)
提交回复
热议问题