Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Using read/write to update a file

by aitap (Curate)
on Oct 19, 2014 at 09:20 UTC ( [id://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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1104292]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (7)
As of 2024-04-16 18:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found