http://www.perlmonks.org?node_id=1104292


in reply to Using read/write to update a file

By the way, there is a mode in Perl to run like sed, editing files in place. Like in sed, this mode is activated with -i switch, described in perlrun. In a Perl program this mode can be controlled via the $^I variable. There is also special ARGV filehandle which iterates over command-line filenames in @ARGV. It's easy to combine these two to edit a file without slurping it into memory:

{ local ($^I, @ARGV) = (".bak", $filename); # $filename is renamed to "$filename.bak" and new "$filename" is open +ed for writing while (<>) { # ARGV filehandle is opened to read from "$filename.bak" s/foo/bar/g; print; } } # at this point @ARGV and $^I are restored to normal

This might look too low-level. There are modules implementing this behaviour: File::Inplace and IO::InSitu. The latter is described in the Perl Best Practices book by Damian Conway.