开发者

How to check if the code exited out of a loop due to a last command?

In a loo开发者_如何学运维p, I have several conditions and if the condition is not satisfied, I exit out of the loop using last syntax.

while (condition) {
    if (possibility 1) {
        ...
        last;
    }

    if (possibility 2) {
        if (possibility 3) {
            ...
            last;
        }
        ...
        last;
    }
}

After I come out of the loop, I need to know whether I used last to exit, or the condition just did not hold true any more. One way of doing that is to write a if statement that negates all the possibilities.

I am looking for some easier/more elegant way to do this.

Is there some Perl variable that stores the information that we exited out of the loop due to last? Or do I need to maintain such a variable myself?


You pretty much just need to set a flag before you exit


You can try and use the value of variable to check, A refactor like this could work:

while (condition) {
    if (possibility 1) {
        ...
        $satisfies_condition = 1;
    }

    if (possibility 2) {
        if (possibility 3) {
            ...
            $satisfies_condition = 3;
        }
        ...
        $satisfies_condition = 2;
    }

    last if $satisfies_condition;
}

Based on the value of $satisifies_condition you can determine your break point


My initial thought on reading the question was just the opposite of what the previous answers have assumed: You don't care which condition caused the loop to exit early, only whether the loop exited early or not. Given that you're using a while loop, this is done quite easily and naturally, without requiring any extra flag variables, unless one of your branches will change condition to make it false before calling last:

while (condition) {
  # blah, blah, blah
}

if (condition) {
  # condition is still true, loop must have exited early due to "last"
} else {
  # loop exited because condition is no longer true
}

If you have early exits which would also make condition false, then you do need to add a flag to track whether the last iteration ran all the way through or not:

my $iter_finished;
while (condition) {
  $iter_finished = 0;
  if (foo) { last };
  if (bar) { condition = 1; last };
  if (baz) { condition = 0; last };
  $iter_finished = 1;
}

if ($iter_finished) {
  # We exited because condition became false
} else {
  # We exited early due to "last" and we know this regardless of condition's value
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜