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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |