替换字符串并在perl中将字符串附加到1个文件中

时间:2013-06-26 05:48:29

标签: perl

我想替换文件中的一行,更换后我想追加另一行。正如你在这里看到的,我必须打开和关闭文件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);

1 个答案:

答案 0 :(得分:0)

Read+Write +<模式下使用Three-arg openopen文件{{1}}。