Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: processing a file once within a nest for loop

by Speedy (Monk)
on Feb 15, 2002 at 23:03 UTC ( [id://145784]=note: print w/replies, xml ) Need Help??

in reply to processing a file once within a nest for loop

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 ""

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( 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.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://145784]
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2024-05-30 07:08 GMT
Find Nodes?
    Voting Booth?

    No recent polls found