Can I "break out" of an if{} block?

Discussion in 'Perl Misc' started by usenet, Jun 9, 2006.

  1. usenet

    usenet Guest

    At any point in a loop, I can "break out" of it with a 'last', or I can
    "break out" of a subroutine with a 'return'.

    Is there a similar way to easily "break out" of an if{} block (without
    a goto)?

    Thanks!
     
    usenet, Jun 9, 2006
    #1
    1. Advertisements

  2. Sure, just put a loop inside the if block:

    if ( $expression ) { {
    last if $oops;
    } }


    John
     
    John W. Krahn, Jun 9, 2006
    #2
    1. Advertisements


  3. Yes, by nesting another if:

    if ( $something ) {
    # do this always
    if ( ! $want_to_last ) { # unless ( $want_to_last ) is "nicer"
    # do this when not "lasting"
    }
    }
     
    Tad McClellan, Jun 9, 2006
    #3
  4. usenet

    Ben Morrow Guest

    Quoth :
    Any block (except for the pseudoblocks which are part of if{}, else{},
    do{} &c.) is treated as a loop which loops once. So just add another set
    of braces and use 'last':

    if (1) {{
    #...
    last if #...
    #...
    }}

    Ben
     
    Ben Morrow, Jun 9, 2006
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.