All,
I can see two ways to reduce duplication of code given the following snippet:
if ( $condition1 ) { if ( $condition2 ) { # Block1 } else { # Block2 } } else { # Block2 repeated again }
The first is the obvious choice to change Block2 into a subroutine. This doesn't feel right to me in this situation for some reason. There are quite a few variables that would need to be passed and keeping track of what is going on is getting difficult. It is obvious to me that refactoring is the right approach but the only alternative to a sub that I can think of is:
{ if ( $condition1 ) { if ( $condition2 ) { # Block1 last; } } # Block2 }

I do not like either of these choices which means I need to back up my refactoring to a higher level. With that said, I am still interested if anyone can think of a different way to eliminate the duplication. I am not going to provide the actual code because I am looking for generic alternatives. I know that given specific conditions there are clear winning options but that's not what I am after for now.

Cheers - L~R

Update: I am an idiot. I actually started out with RazorbladeBidet's solution below, but changed it because it didn't work as evaluation of the conditions has side effects. When I ended up with duplicated code I tried removing the duplicated code instead of the side effects. That's why a subroutine didn't feel right and it is also why refactoring at a higher level is the right thing to do.

Thanks for helping me see the forest through the trees.


In reply to Better solution for code reduction? by Limbic~Region

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.