Perl Breaking out of an If statement

  • Put it inside an empty for() loop, and add last; everywhere you want to break out AND after the if. A bit ugly but works. Make sure to add comments to explain the trick.

    for (;;) {
        if (condition) { 
            #code
            last if another_condition;
        }
        last;
    }
    
  • use goto and label a statement after your loop for that goto. Be forever damned.

  • Extra block inside the if (e.g. if () {{ code }}). May be hard to read for novices but OK if accompanied by a comment.

  • your own solution: block around if. Not very obvious readability-wise.

  • your own solution: subroutine with return.

    Frankly, unless the cost of calling a sub matters performane wise, this is the cleanest solution as far as readability.


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";
  }
}