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

In a loop, I have several conditions, and if the condition is not met, I exit the loop using the lastsyntax.

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

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

After I left the loop, I need to know if I used the latter to exit, or the condition simply was not confirmed. One way to do this is to write an if statement, which overrides all the possibilities .

I am looking for a simpler / elegant way to do this.

Is there some kind of Perl variable that stores the information we left the loop because of the latter? Or do I need to maintain such a variable myself?

+3
source share
3 answers

,

+5

. :

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

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

    last if $satisfies_condition;
}

$satisifies_condition,

0

, , , : , , . , while, , - , condition, 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
}

, condition false, , , :

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 value
}
0

All Articles