How to add and replace rows in a linear array using perl

I want to edit the file by adding some line and replacing some others. I am trying to work with an array that contains my file line by line, i.e.

    my $output_file_string = `cat $result_dir/$file`;
    my @LINES = split(/\n/, $output_file_string);

I have a hash table of strings that I want to find in the file, and either replace them, or add an extra line after them. I wrote the following code to recognize strings:

        foreach my $myline (keys %{ $hFiles_added{$file} }) { 
            foreach my $line ( @LINES) {
                  if ($line =~ /\Q$myline\E/) {
                       ### here should be a code for adding a new line after the current line ###
                  }
             }
        }
        #### here should be a code to return the array to the output file ####

I can’t understand how to add / replace parts and how to save the edited file back to the file (and not the array

thanks shahar

+4
source share
3 answers

Use splice to change the contents @LINES.

open print, @LINES .

, flock.

, Tie:: File.

seek truncate.

FAQ Perl - , ?

, :

my @LINES = `cat $result_dir/$file`;
+3

, , $edit.

use strict;
use warnings;

sub edit_file {
  my $func = shift;

  # perl magic for inline edit
  local @ARGV = @_;
  local $^I = "";
  local $_;

  while (<>) {
    $func->(eof(ARGV));
  }
}


my $edit = sub {
  my ($eof) = @_;

  # print to editing file
  print "[change] $_";
  if ($eof) {
    print "adding one or more line to the end of file\n";
  }
};
edit_file($edit, "file");
+1

You can use the File :: Slurp module to read, write, add, edit lines, insert new lines into a file, and many others.

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
0
source

All Articles