Paul Rousseau wrote:
Hello,

I want to open a text file, look for a specific string, replace it with a new string, and write the line out to another file. For lines not containing the specific string, I want to write out as is.

I was wondering if it is possible to do it with a map or splice or grep command rather than a foreach loop.

Well, you didn't use a foreach loop in your sample below, you used a while loop. But yes, it is possible to do it with a map, not a grep or a splice.

Don't confuse the Perl grep with the Unix command. The perl grep works on a single string, while the Unix grep repeats the same match over multiple lines. Also, grep only finds strings; it doesn't do any replacements.

A splice is for inserting or removing list elements - not what you want to do.
Perhaps, I should be looking at some executable that replaces one string with another within a file?

I have resorted to a foreach loop.
Nope, you used a while loop. You could have just as easily used a foreach, though. Frankly, I think it's a perfectly appropriate application of a while loop. I wouldn't say you 'resorted' to it.
Here is a snippet of my code:

          $currnodename = "AMACHINE";
          $oldnodename = "BMACHINE";
          $infile = "$ENV{FT}\\qld\\$msg.qli";
          $outfile = $ENV{TEMP} . "\\$task.tmp";

          open (INFILE, "<$infile") || die "Can not open $infile";
          open (OUTFILE, "+>$outfile") || die "Unable to open $outfile";
          while ($inline = <INFILE>)
             {
              chomp $inline;
The chomp should not be there. You still want the newline in the output string, right?
              $inline =~ s/$oldnodename/$currnodename/g;
              print OUTFILE $inline;
             }
          close INFILE;
          close OUTFILE;

Here's your loop rewritten using map:

@lines = <INFILE>;
map { s/$oldnodename/$currnodename/g; $_ } @lines;
print OUTFILE @lines;

If for some reason you wanted to be able to reuse the original lines, so you could do a different substitution on them in another pass, you could preserve them thusly:

@inlines = <INFILE>;
map { s/$oldnodename/$currnodename/g; $_ } (@outlines = @inlines);
print OUTFILE @outlines;

Finally, here's your loop, actually written as a foreach:

@lines = <INFILE>;
foreach $line (@lines)
{
   $line =~ s/$oldnodename/$currnodename/g;
}
print OUTFILE @lines;

--
Lyle Kopnicky
Software Project Engineer
Veicon Technology, Inc.

_______________________________________________
Perl-Win32-Users mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to