Jun 26, 2013, 3:12 PM
Post #5 of 5
Re: [perlFun] break out of foreach loop and GOTO somewhere (help)
[In reply to]
Won't this take me to NEWPLACE (when that condition is met) but then continue with the remainder of the foreach once the stuff in NEWPLACE is done?No, it won't, if you use a goto go break out of a loop, then you're out of the loop for good.
How do I completely break out of that foreach and then skip down to NEWPLACE?As noted above, a goto would do it, but don't use goto, don't do that. Perl has all the powerful instruments needed to do good and efficient structured programming, and a goto is just bad because it breaks structured programming.
You should know that the gods kill a puppy each time a programmer on the earth uses a goto. In brief, goto is evil (well, only 99.9% of the time, there are extremely rare cases where it could make sense, but only if you really know the usually much better alternatives and have a very good specific reason to do so) ! I have been programming in Perl for more than 10 years and have never found the need to use a goto (and also never used a goto in C programming in the preceding 10 years).
There are several statements in Perl that allow you to break out of a loop or modify the behavior of a loop, such as last, next and continue, depending on what you need to do.
Now, I am not a religious fanatic against goto's. In another programming language that I am using very commonly, I am frequently using goto's. But this is just because that language does not have the equivalent of a next statement when looping on the records of a database, so I use a goto to go straight to the end of the loop when some special condityions are met, in other words I use a goto in that language only to emulate a next statement, a case where it is legitimate because it does not break strutured programming.
(To tell the truth, I am old enough to have used older languages such as older Fortran versions and some versions of Basic, and also or course various assembly languages, where goto was necessary. But this is no longer required, and is certainly not useful in Perl and other modern languages availabe today).
In brief, I warn you against goto: if you feel like needing it, it is probably because you program is poorly structured. Rework the structure, refactor it.
(Just a final point for the sake of completeness. There is in Perl one very special and unusual form of goto which has very very little to do with what most people associate with goto (I believe it should have been given a different name), really a form of black magic. That specific form of goto does make sense when needed, but that is so rare that it is better to just forget about it: if you were anywhere near to understand these extremely specific cases, you would not ask the question you just asked.)