I want to edit a file by adding some line and replacing some others. I\'m trying to work with an array that contains my file line by line, i.e
my $outpu
You can use the module File::Slurp to read, write, append, edit the lines, insert new lines in the file and many other things.
http://search.cpan.org/~uri/File-Slurp-9999.19/lib/File/Slurp.pm
use strict;
use warnings;
use File::Slurp 'write_file', ':edit';
my $file = './test.txt';
#The lines you want to change with their corresponding values in the hash:
my %to_edit_line = ( edit1 => "new edit 1", edit2 => "new edit 2" );
foreach my $line ( keys %to_edit_line ) {
edit_file_lines { s/^\Q$line\E$/$to_edit_line{$line}/ } $file;
}
#The lines after you want to add a new line:
my %to_add_line = ( add1 => 'new1', add2 => 'new2' );
foreach my $line ( keys %to_add_line ) {
edit_file_lines { s/^\Q$line\E$/$line\n$to_add_line{$line}/ } $file;
}
#The lines you want to delete:
my %to_delete_line = ( del1 => 1, del2 => 1 );
foreach my $line ( keys %to_delete_line ) {
edit_file_lines { $_ = '' if /^\Q$line\E$/ } $file;
}
#You can also use this module to append to a file:
write_file $file, {append => 1}, "the line you want to append";
The original file test.txt had the following content:
zzz
add1
zzz
del1
zzz
edit1
zzz
add2
zzz
del2
zzz
edit2
zzz
After running the program, the same file has the following content:
zzz
add1
new1
zzz
zzz
new edit 1
zzz
add2
new2
zzz
zzz
new edit 2
zzz
the line you want to append