Problems? Is your data what you think it is? | |
PerlMonks |
Re: Multiline search and replace in file(s)by haukex (Archbishop) |
on Aug 09, 2020 at 08:03 UTC ( [id://11120515]=note: print w/replies, xml ) | Need Help?? |
You can use the following pattern to slurp and spew a file:
(Slurping can also be shortened to my $data = do { open my $fh, '<', $modfile or die $!; local $/; <$fh> };, though that's a bit less readable if you're not used to it). Or you can use a nice module like Path::Class or Path::Tiny:
Or you can use a oneliner (see also $^I):
Or you can use my module File::Replace for atomic updates when the filesystem supports it:
Or you can open the file in read-write mode, truncate it after reading, and then write it - though note I see this being done very rarely. (It's useful if you want to flock the file while editing. That can be as simple as adding use Fcntl qw/:flock/; at the top of the code and flock($fh, LOCK_EX) or die "flock $modfile: $!"; immediately after the open. Keep in mind that flock locks are merely advisory, though!)
Note that glob has several caveats, though as shown in this code it's ok. Updates: Added info on flock and $^I.
In Section
Seekers of Perl Wisdom
|
|