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