OK, so no one really likes goto. However, I have come to a situation where goto would probably the easiest solution to a problem I have.

Before, my code looked like this (I know that next already is a form of goto, but I think it's considered "OK" to use it).

LABEL1: foreach my $a (@b) { if (...) { next LABEL1; } do_something(); if (...) { next LABEL1; } do_something_else(); if (...) { next LABEL1; } do_something_again(); }

Now however I want to add a call to a subroutine to the end of the foreach loop. This subroutine (let's call it perform_cleanup) should always be invoked, even in case we're going to the next loop iteration early. So my easiest solution with goto would be to change each "next LABEL1" to "goto LABEL1" and add the following to the end of the foreach loop:

LABEL1: perform_cleanup();

I'm asking this out of curiosity. In this case what would you say is the "cleanest" solution to do this? Do you think using goto in this case is OK or would you rewrite it?


In reply to Avoiding goto by elTriberium

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.