How to add and replace lines in a line array with perl

后端 未结 3 646
北恋
北恋 2021-01-19 08:11

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         


        
3条回答
  •  再見小時候
    2021-01-19 08:25

    I would suggest another approach where file is processed line by line, and lines are modified within user specified $edit function.

    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");
    

提交回复
热议问题