Perl Breaking out of an If statement

David W. picture David W. · Jun 11, 2013 · Viewed 38.1k times · Source

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 a loop I can do this:

while (something ) {
    last if $some_condition;
    blah, blah, blah
    ...
}

However, can I do the same with an if statement?

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

I know I could put the if statement inside a block, and then I can break out of the block:

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

Or, I can create a subroutine (which is probably better programmatically):

if ( some_condition ) {
    run_subroutine();
}

sub run_subroutine {
    blah, blah, blah
    return if $some_other_condition;
    blah, blah, blah
    ...
}

But is there any way to exit an if condition?


Resolution

The question came up because I was helping someone with their code. Inside a fairly long if statement, there were several other if statements embedded in it. The code looked something like this:

 if ( $condition1 ) {
    blah, blah, blah;
    if ( not $condition2 ) {
       blah, blah, blah;
       if ( not $condition3 ) {
          blah, blah, blah;
       }
    }
}

I thought the whole thing could be made more readable by doing this:

if ( $condition1 ) {
    last if $condition2;
    blah, blah, blah;
    last if $condition3;
    blah, blah, blah;
}

This shows that the normal flow of the if statement is standard, but under certain conditions, the if statement was exited early -- much like using last or next in a while or for loop to exit the loop.

I liked mpapec's solution of using a label -- even if I don't use the label itself. The label is a description of my if:

IF-UNDER-CONDITION1:
{
    if ( $condition1 ) {
        last if $condition2;
        blah, blah, blah;
        last if $condition3;
        blah, blah, blah;
    }
}

Although it isn't a standard coding technique, the flow of the code is obvious enough that a typical low-level Perl developer (the one that has to maintain this code after I leave) could figure out what the code is doing and maintain it. They may even learn something in the process.

Answer

mpapec picture mpapec · Jun 11, 2013

You can use basic block which is subject to last, next and redo, so there is possible break from it.

if ($condition) {EXIT_IF:{

   last EXIT_IF; # break from code block

   print "never get's executed\n";
}}

EXIT_IF: {
  if ($condition) {

     last EXIT_IF; # break from code block

     print "never get's executed\n";
  }
}