This is driving me nuts. Help?
It looks to me like inside a Perl foreach
loop, variables outside of a replacement pattern change as expected, but a variable inside a replacement pattern gets "stuck". It's almost as though when perl encounters a s///
replacement pattern inside a foreach
code block, it interpolates the replacement pattern contents the first time through the loop and never again.
Here is some test code:
#!/usr/bin/perl
@replacements=("a", "b", "c");
@input=("xxletterxx");
foreach $replacement (@replacements) {
foreach $line (@input) {
$line=~s/xxletterxx/$replacement/g;
print "R: $replacement\n";
print "L: $line\n";
}
}
I think it should print this:
R: a
L: a
R: b
L: b
R: c
L: c
...but instead it prints this:
R: a
L: a
R: b
L: a <--- Why isn't this 'b'?
R: c
L: a <--- Why isn't this 'c'?
Notice how the "L" value is still "a" inside the replacement pattern even though elsewhere in the code block it's changing with the members of @replacements
?
Why is that?
I feel like Perl is suddenly broken, or I've lost my mind.
It almost seems like this DOS behavior is occurring in perl.