Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re: Using read/write to update a file

by aitap (Curate)
on Oct 19, 2014 at 09:20 UTC ( #1104292=note: print w/replies, xml ) Need Help??

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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1104292]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2018-07-18 09:07 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (388 votes). Check out past polls.