Well the first problem you are likely having is that with your regex, when you have something like static replace [something] and [another] thing it is grabbing the longest it can and therefore $replace ends up being something] and [another. A simple character class along the lines of [^]] (grabs everything but the closing bracket) instead of just . should do it

The second problem I see is that when the replacement is done, it leaves the brackets there, so if you do iterate over it again, it will proceed to attempt to replace the replacements, which will likely not have any corresponding value in the hash, and therefore be undefined, and leave the spot empty. Adding escaped brackets into the the first half of the substitution will take care of that problem

So, after all that here is my test case which should demonstrate one way to do this with a while loop and hashes as you first mentioned:

$loop_line = "static replace [something] and [another]\n"; %replace_table = ('something','this','another','that'); print $loop_line; while ($loop_line =~ /\[([^]]*)\]/) { my $replace = $1; my $replacement = $replace_table{$1}; $loop_line =~ s/\[$replace\]/$replacement/; }; print $loop_line;

update: bleh, took too long writing this, so I got beaten to it :( ahh well, if nothing else I got some practice on RegExs and Debugging :)


In reply to Re: Replacing multiple matches by Koosemose
in thread Replacing multiple matches by alongwor

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.