问题
Possible Duplicate:
Need perl inplace editing of files not on command line
I have already a working script that edit my log file but i'm using a temporary file, my script working like that:
Open my $in , '<' , $file;
Open my $out , '>' , $file."tmp";
while ( <in> ){
  print $out $_;
  last if $. == 50;
}
$line = "testing";
print $out $line;
while ( <in> ){
  print $out $_;
}
#Clear tmp file
close $out;
unlink $file;
rename "$file.new", $file;
I would like edit my file without creating a tmp file.
回答1:
Use the inplace-editing magic:
#!/usr/bin/env perl
use autodie;
use strict;
use warnings qw(all);
my $file = 'test';
# setup the inplace operation
@ARGV = ($file);
# keep backup at "$file.bak"
$^I = '.bak';
# inplace editing takes over STDIN/STDOUT
while (<>){
    print;
    if ($. == 50) {
        my $line = "testing\n";
        print $line;
    }
}
    回答2:
Read all lines, then modify the one you want to modify, and write them all back to the original file. You can optionally use modules like File::Slurp for one-line methods for reading and writing all lines.
For example:
use File::Slurp;
my @lines = read_file("yourfile.txt");
$lines[$line_number_to_modify] = "whatever\n";
write_file("yourfile.txt", @lines);
    来源:https://stackoverflow.com/questions/13971449/how-to-edit-a-line-in-txt-file-in-perl-without-using-a-tmp-file