The reason why your code works as it does, is because when you use
for or
map, the loop variable is essentially a pointer to the
value, not a copy of the value. So, if you change the value of
the loop value, it changes the corresponding array element. This
is the same behavior whether your loop variable is
$_
or a lexical created with
my.
The easiest way to patch this to make it work is to copy the
loop variable into another temporary variable before doing the
substitution:
# Warning, untested code below.
for my $j(@templ) {
my $k = $j;
$k =~ s/^(\w+)\@DOMAIN$/$1\@$i/;
print FH $k;
}
# Or:
foreach (@templ) {
my $j = $_;
$j =~ s/^(\w+)\@DOMAIN$/$1\@$i/;
print FH $j;
}
Some people don't like temporary variables, especially in
cases like this, where it looks like you could remove the
variable with no ill effect to the code (but you can't).
But, since this is perl, there are other ways to do it.
One would be to match $j and then do the replacement in the
print statement instead of using s///:
# Warning, untested code below.
for (@templ) {
/^(\w+)\@DOMAIN$/ and print FH "$1\@$i"
or print FH; # implicitly prints $_ as usual
}
# Or if you prefer "if":
for (@templ) {
if (/^(\w+)\@DOMAIN$/) {
print FH "$1\@$i";
}
else {
print FH;
}
}
I hope these help.
Alan
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.