Most efficient way to write over file after reading

Posted by Ryan McClure on Stack Overflow See other posts from Stack Overflow or by Ryan McClure
Published on 2014-08-05T19:37:08Z Indexed on 2014/08/23 22:21 UTC
Read the original article Hit count: 243

Filed under:
|

I'm reading in some data from a file, manipulating it, and then overwriting it to the same file. Until now, I've been doing it like so:

open (my $inFile, $file) or die "Could not open $file: $!";

    $retString .= join ('', <$inFile>); 
    ...

close ($inFile);

open (my $outFile, $file) or die "Could not open $file: $!";

    print $outFile, $retString;

close ($inFile);

However I realized I can just use the truncate function and open the file for read/write:

open (my $inFile, '+<', $file) or die "Could not open $file: $!";

    $retString .= join ('', <$inFile>); 
    ...
    truncate $inFile, 0;
    print $inFile $retString;

close ($inFile);

I don't see any examples of this anywhere. It seems to work well, but am I doing it correctly? Is there a better way to do this?

© Stack Overflow or respective owner

Related posts about perl

Related posts about file-io