http://qs321.pair.com?node_id=16533

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm really only "good" at javascript, but here goes. I'm using a while statement in my program, and I want to be able to a) make it stop where it is and start over at the beginning of the while statement, and b) make it quit the while statment and execute whatever directly follows this. In JavaScript this is accomplished by using the break and continue statements. How do you do this in perl and what is the format? Thanx.

Replies are listed 'Best First'.
Re: break/continue statements
by ivey (Beadle) on Jun 06, 2000 at 07:17 UTC
    what you want are next and last:
    while ($some_condition == 1) { if ($want_to_start_over) { next; } elsif ($want_to_quit) { last; } &do_whatever_else; }
Re: break/continue statements
by zodiac (Beadle) on Jun 06, 2000 at 13:51 UTC
    you might also want to have a look at redo and continue.
    this "code" shows where next, redo and last jump, if continue is present:
    while (EXPR) { REDO: #body of while block } continue { NEXT: #body of next block } LAST:
    without continue it looks slightly different:
    NEXT: while (EXPR) { REDO: # body of while block } LAST:

    perls next, redo and last can also be used to get out of a deeper level of iteration:

    # nb this is stupid code that shortens lines (a char at a time) # and prints the result, until it finds a z at the first pos. LINE: foreach(<>) { while(s/^.//) { print; last LINE if /^z/; #this also breaks the foreach loop. -- it j +umps to the print "done"; statement } } print "done";
Re: break/continue statements
by plaid (Chaplain) on Jun 06, 2000 at 07:19 UTC
    In perl, this would be done with the last and next commands, which act just like break and continue, respectively. Follow the links for detailed usage of these constructs.