
I ran into an interesting side-effect with the foreach loop in Perl today. I’m surprised that I haven’t hit this before, but it may be a subtle enough issue that it only pops up under the right circumstances. Here’s a sample program that we’ll use as an example:
#!/usr/bin/perl -w
use strict;
my @array = ("Test NUM", "Line NUM", "Part NUM");
for (my $i=0; $i < 3; $i++)
{
foreach (@array)
{
s/NUM/$i/;
print "$_\n";
}
print "------\n";
}
What should the output for this little script look like? Here’s what I assumed it would be: