Perl Breaking out of an If statement

后端 未结 7 840
深忆病人
深忆病人 2021-02-05 03:50

This one just came up: How do I break out of an if statement? I have a long if statement, but there is one situation where I can break out of it early on.

In

7条回答
  •  有刺的猬
    2021-02-05 04:06

    I was inspired by DVK's answer to play around, and I came up with this variant that works at least on Perl 5.26.1:

    for( ; some_condition ; last ) {
        blah, blah, blah
        last if $some_other_condition; # No need to continue...
        blah, blah, blah    
    }
    

    Per perlsyn, this is equivalent to:

    while (some_condition) {
        blah, blah, blah
        last if $some_other_condition; # No need to continue...
        blah, blah, blah    
    } continue {
        last;
    }
    

    In a continue block, last has the same effect as if it had been executed in the main loop. Therefore, the loop will execute zero or one times, depending on some_condition.

    Tests

    perl -E 'my ($cond, $other)=(X, Y); 
             for(;$cond;last) { say "hello"; last if $other; say "goodbye" }'
    

    has the following results, for various X and Y values:

    X Y   Prints
    -----------------------
    0 0   (nothing)
    0 1   (nothing)
    1 0   hello, goodbye
    1 1   hello
    

提交回复
热议问题