The_Last_Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi there, My problems lies with being unable to figure out how to replace a particular word/line with another word/line, and then write the data which was read in from the first file to another file with the replacement word rather than the orignal word. Here is what i have done so far in a shortcut
open my $file, $firstTextFile or die "Unable to open"! while(<$file>){ if($_ =~ /hue/){ $_ =~ s/hue/someword/g; // How do i now write to a text file all the previous things in the fi +rst text file except for the word hue being replaced with the word so +meword in the new text file? } }
  • Comment on Writing all relevant data in one file to a new file with adjustments
  • Download Code

Replies are listed 'Best First'.
Re: Writing all relevant data in one file to a new file with adjustments
by pme (Monsignor) on Feb 08, 2015 at 20:43 UTC
    Just open another filehandler and print the lines into it.
    my $infilename = 'infile.txt'; my $outfilename = 'outfile.txt'; open my $infile, "<$infilename" or die "Unable to open $infilename $!" +; open my $outfile, ">$outfilename" or die "Unable to open $outfilename +$!"; while (<$infile>) { s/hue/someword/g; print $outfile $_; } close $infile; close $outfile;
Re: Writing all relevant data in one file to a new file with adjustments
by Laurent_R (Canon) on Feb 08, 2015 at 22:09 UTC
    pme has given the solution and also corrected implicitly what I am just going to say, but I want to comment it explicitly. When you write:
    if($_ =~ /hue/){ $_ =~ s/hue/someword/g; }
    you don't really need that if conditional: the substitution operator $_ =~ s/hue/someword/g; will anyway do the substitution only if the input line matches /hue/, so that the three code lines above can be summarized to
    $_ =~ s/hue/someword/g;
    It can actually be simplified further by noting that that the substitution operator works by default on $_, so that it can be rewritten:
    s/hue/someword/g;
    but not everyone agrees with that further simplification, some people prefer to explicitly use the $_ variable and the =~ binding operator. The same simplification could have been done in the if conditional (if (/hue/) { # ...), but there is no point of discussing that further since it has already been removed.

    Je suis Charlie.