> On Jan 28, 2016, at 1:37 AM, Frank Larry <[email protected]> wrote:
>
> Hi Team,
>
> could you please let me? i have a file which contains "Debug", i would like
> to replace debug to "Error", when i ran the below program the out showing
> Error message but how to save the output with new changes. Could you please
> tell me how to fix it?
The way to do this within a larger Perl program is to open a new output file,
copy all of the possibly-modified lines to this file. Then you can rename the
new file to the same name as the old file, and perhaps rename the old file as
well and keep it around as a backup.
>
> open(FILE, "<filter.txt") or die "Can’t open $!\n”;
The three-argument version of open is preferred here, and let’s put the file
name in a variable and use a lexical variable for the file handle (untested):
my $filename = ‘filter.txt’;
open( my $in, ‘<‘, $filename ) or die(“Can’t open $filename for reading: $!”);
# create a new file
my $newfile = $filename . ‘.new’;
open( my $out, ‘>’, $newfile ) or die(“Can’t create $newfile: $!”);
>
> while($line = <FILE>){
while( $line = <$in> ) {
>
> print "Before substituting: ", $line ,"\n";
> $line =~ s/Debug/Error/g;
> print "After substituting : ", $line , "\n”;
print $out $line;
>
> }
>
> close(FILE);
close($in);
close($out) or die(“Error writing to output file $newfile: $!”);
# rename the old file
my $savefile = $filename . ‘.sav’;
rename $filename, $savefile;
# rename the new file
rename $newfile, $filename;
Jim Gibson
[email protected]
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/