title: Perl Breaking out of an If statement
body: <p>This one just came up: How do I break out of an <code>if</code> statement? I have a long if statement, but there is one situation where I can break out of it early on.</p>
  <p>In a loop I can do this:</p>
  <pre><code>while (something ) {
      last if $some_condition;
      blah, blah, blah
      ...
  }
  </code></pre>
  <p>However, can I do the same with an if statement?</p>
  <pre><code>if ( some_condition ) {
      blah, blah, blah
      last if $some_other_condition; # No need to continue...
      blah, blah, blah
      ...
  }
  </code></pre>
  <p>I know I could put the <code>if</code> statement inside a block, and then I can break out of the block:</p>
  <pre><code>{
      if ( some_condition ) {
          ...
          last if $some_other_condition; # No need to continue...
          blah, blah, blah
          ...
      }
  }
  </code></pre>
  <p>Or, I can create a subroutine (which is probably better programmatically):</p>
  <pre><code>if ( some_condition ) {
      run_subroutine();
  }
  
  sub run_subroutine {
      blah, blah, blah
      return if $some_other_condition;
      blah, blah, blah
      ...
  }
  </code></pre>
  <p>But is there any way to exit an <code>if</code> condition?</p>
  <hr />
  <h2>Resolution</h2>
  <p>The question came up because I was helping someone with their code. Inside a fairly long <code>if</code> statement, there were several other <code>if</code> statements embedded in it. The code looked something like this:</p>
  <pre><code> if ( $condition1 ) {
      blah, blah, blah;
      if ( not $condition2 ) {
         blah, blah, blah;
         if ( not $condition3 ) {
            blah, blah, blah;
         }
      }
  }
  </code></pre>
  <p>I thought the whole thing could be made more readable by doing this:</p>
  <pre><code>if ( $condition1 ) {
      last if $condition2;
      blah, blah, blah;
      last if $condition3;
      blah, blah, blah;
  }
  </code></pre>
  <p>This shows that the normal flow of the <code>if</code> statement is standard, but under certain conditions, the <code>if</code> statement was exited early -- much like using <code>last</code> or <code>next</code> in a <code>while</code> or <code>for</code> loop to exit the loop.</p>
  <p>I liked <a href="https://stackoverflow.com/a/17053749/368630">mpapec's</a> solution of using a label -- even if I don't use the label itself. The label is a description of my <code>if</code>:</p>
  <pre><code>IF-UNDER-CONDITION1:
  {
      if ( $condition1 ) {
          last if $condition2;
          blah, blah, blah;
          last if $condition3;
          blah, blah, blah;
      }
  }
  </code></pre>
  <p>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.</p>