Hi, I found that this works, assuming that the module is installed. #!/usr/bin/perl use warnings; use strict; use File::Slurp qw ( :edit ); # my $file_to_edit = 'path-to-file.txt'; # my $word_to_edit = "Debug"; my $new_word = "Error"; # edit_file { s/$word_to_edit/$new_word/g } ( $file_to_edit ); #
This will work if you have the word Debug, Debug_ etc etc You can just use s/Debug/Error/g but I like the variables as it allows flexibility if the script was to expand to further uses Hope that helps, Jon On Thu, Jan 28, 2016 at 3:41 PM, Jim Gibson <j...@gibson.org> wrote: > > > On Jan 28, 2016, at 1:37 AM, Frank Larry <frankylarry2...@gmail.com> > 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 > j...@gibson.org > > > > > -- > To unsubscribe, e-mail: beginners-unsubscr...@perl.org > For additional commands, e-mail: beginners-h...@perl.org > http://learn.perl.org/ > > >