I don't know the Text::Balanced module, so I can't tell you if there is a shortcut somewhere. But I can tell you why your regexes only work once.

First I would suggest leaving out all the unnecessary escapes. This makes your regex much more readable and less toothpicky ... $text =~ s/<!--(.*?)}(.*?)-->/<!--$1 endbrace $2-->/gxs;This matches a whole comment and within the comment the first closing brace is matched and replaced. Due to the /g modifier the regex continues searching, but not at the same starting character but the next one. So the same comment cannot match twice which is required to match multiple closing braces. The same goes for multiple opening braces.

You could fix that behaviour with the following construct 1 while s///; This repeats the whole substitution until no more substitution could be performed. It does the trick, but can be quite inefficient on large files as the whole text has to be search multiple times. Imagine e.g. a last line like this || }}}}}}}}}}

That's why I would go a different way for dealing with the comments - line by line simplifies things

foreach (@lines) { chomp; if (/^\s*\|\|/) { # is a comment s/}/endbrace/g; s/{/openbrace/g; s/^\s*||/<!--/; $_ .= "-->"; } }
The backsubstitution works similarly if you work on lines again

Remark: I hope you don't have to deal with comment lines like this || min-->max++; because then things get tricky ...

-- Hofmator


In reply to Re: Problem with skipping comment by Hofmator
in thread Problem with skipping comment by tshabet

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.