Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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


In reply to Re: processing a file once within a nest for loop by ferrency
in thread processing a file once within a nest for loop by c

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (4)
As of 2024-03-29 10:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found