append a text on the top of the file

前端 未结 6 855
借酒劲吻你
借酒劲吻你 2020-12-20 16:29

I want to add a text on the top of my data.txt file, this code add the text at the end of the file. how I can modify this code to write the text on the top of my data.txt f

6条回答
  •  执念已碎
    2020-12-20 16:53

    Your syntax is slightly off deprecated (thanks, Seth):

    open(MYFILE, '>>', "data.txt") or die $!;
    

    You will have to make a full pass through the file and write out the desired data before the existing file contents:

    open my $in,  '<',  $file      or die "Can't read old file: $!";
    open my $out, '>', "$file.new" or die "Can't write new file: $!";
    
    print $out "# Add this line to the top\n"; # <--- HERE'S THE MAGIC
    
    while( <$in> ) {
        print $out $_;
    }
    close $out;
    close $in;
    
    unlink($file);
    rename("$file.new", $file);
    

    (gratuitously stolen from the Perl FAQ, then modified)

    This will process the file line-by-line so that on large files you don't chew up a ton of memory. But, it's not exactly fast.

    Hope that helps.

提交回复
热议问题