You are right about having to protect the values in @tmpl. Once you change the word DOMAIN to the first @subs value, in your original code you have changed your template itself and can no longer substitute for DOMAIN -- in your case you now need to substitute for "itchy.foo"
Try this sample code, where I substituted for the $j variable name something a bit more descriptive, and before each potential replacement saved each template string to a new "str_for_subbing" (and made up an "input" for the template file so I could see some real output).
#!/usr/bin/perl
use strict;
my @subs = qw(itchy.foo scratchy.bar homer.bab);
my @tmpl = ("To: webmaster\@DOMAIN", "Dear Sir or Madam:", "You have
+won \$1,000,000!");
my ($sub, $str, $str_for_subbing);
for $sub(@subs) {
open(FH,">virt.$sub") or die;
# Assume @templ in your code should have been @tmpl
# -- good reason to use strict!
foreach $str (@tmpl) {
$str_for_subbing = $str;
$str_for_subbing =~ s/DOMAIN/$sub/g;
print "$str_for_subbing\n";
print FH "$str_for_subbing\n";
}
close(FH)
}
If you don't assign each $str to a $str_for_subbing, you do change the value of $str in the template on the first substitution for DOMAIN, which was not your intent. Substituting in a "copy" of each string saves you this grief.
Live in the moment.