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

is there any way to get out of a foreach or a while loop? in other words to break the loop

Replies are listed 'Best First'.
Re: out of loop
by the_slycer (Chaplain) on Mar 31, 2001 at 02:20 UTC
    while (foo){ last if bar; #rest of code }
Re: out of loop
by clintp (Curate) on Mar 31, 2001 at 04:37 UTC
    die, goto, last, return, exit, dump, "kill 9, $$" and lots more I'm sure.
Re: out of loop
by MeowChow (Vicar) on Mar 31, 2001 at 02:27 UTC
    This will also do the trick:
    while ($foo) { die if $bar; ... } # just kidding :)
      Actually, I do this all the time:
      eval { for my $file (@files) { open FILE, $file or die 'Cannot open file'; ... } }; warn 'Could not process all files' if $@;
        I sincerely hope that you change this habit.

        Now.

        Do you like starting debugging without having a clue which file you had problems on, or what helpful information was in $!? How about your co-workers?

        For these reasons and more, this is something that I feel extremely strongly on. I do not like working with code written by people who did not understand that this matters. I do not want to depend on people who do not appreciate this. Not knowing that trying to trap good error messages is important is one thing, but refusing to learn is a fireable offence in my books.

        (And yes, the strength that I put into that statement does reflect a few very miserable late nights that I do not want to repeat. Ever.)