0

我想替换文件中的一行,替换后我想追加另一行。正如您在此处看到的,我必须打开和关闭文件 2 次。我可以通过只打开一次文件来做到这一点吗?谢谢

  use strict;
  use warnings;

   open(FILE,"tmp1.txt") || die "Can't open file: $!";
   undef $/;
   my $file = <FILE>;
   my @lines = <FILE>;
   my @newlines;
   for each(@lines) {
     $_ =~ s/hello/hi/g;
     push(@newlines,$_);
    }
   close(FILE);
   open(FILE, "> tmp1.txt ") || die "File not found";
   print FILE @newlines;
  close(FILE);

  open(FILE,"tmp1.txt") || die "Can't open file: $!";
  undef $/;
  my $file = <FILE>;
  my @lines = <FILE>;
  my $first_line = "hi";
  my $second_line = "sun";
  my $insert = "good morning";


  $file =~ s/\Q$first_line\E\n\Q$second_line\E/$first_line\n$insert\n$second_line/;


  open(OUTPUT,"> tmp3.txt") || die "Can't open file: $!";
  print OUTPUT $file;
  close(OUTPUT);
4

1 回答 1

0

使用参数open并以Read+Write.+<

于 2013-06-26T05:54:08.357 回答