Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

break/continue statements

by Anonymous Monk
on Jun 06, 2000 at 06:12 UTC ( #16533=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://16533]
Approved by root
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (2)
As of 2022-07-04 08:17 GMT
Find Nodes?
    Voting Booth?

    No recent polls found