In cases like this the flip-flop operator ( '..' in scalar context, see perlop) can really help to clean things up by eliminating the need to track state. For example, the entire body of your while loop can be replaced with this:

if( /$start/ .. /$finish/ ) { $content .= $_; }
Now that is easier and more maintainable!

The snippet above will append $_ to $content anytime $_ matches $start and until it matches $finish. Note that $content will include the patterns within $start and $finish, however, so a simple regex at the end can be used to eliminate them:

$content =~ m/$start(.*)$finish/s;
This does, of course, simply reduce to the examples above which use the s modifier to allow '.' to match newlines, but it illustrates how the flip-flop operator could be used in this situation. No more need for $phase, no more funky loop control in nested 'if' statements, and no manual resetting of $_.

See also the very nice discussion in Flipin good, or a total flop?.


In reply to Re^2: help match this by bobf
in thread help match this by Anonymous Monk

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.